cordier 发表于 2008-7-10 14:45

关于C程序,在C++编译器下编译

以下C程序代码:

/*************************************************************************
*输入某个字符串,统计此字符串在文本文件中的个数,并统计此文件单词的数目
*环境:D盘下面有一个文件test.txt,文件内容:this is a apple this is
*************************************************************************/
#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
int count=0;   /*统计apple 出现的次数*/
int word=0;    /*统计单词的数目*/
char *input;   /*输入字符串*/
char *text;    /*从文本中读取的一个个单词*/
FILE *fp;

fp=fopen("d:\\test.txt","r");
if (fp==NULL)
  {
   printf("File Open Error:\nPress any key to exit:");
   getch();
   exit(1);
  }
printf("input a string for search:");
scanf("%s",input);   /*输入字符串*/

do
  {
   fscanf(fp,"%s",text); /*从文件中读入一个单词*/
   word++;  /*单词计数加1*/
   if (strcmp(text,input)==0)     /*找到输入的字符串*/
    count++;
  }while(!feof(fp));
printf("word=%d\nfind string:%s  %d times\n",word,input,count);

getch();
}


我在tc2.0和Win-tc下好好的,但是到vc++6.0下面编译有三个警告,可以运行,但是运行到scanf和fscanf就会出现弹出关闭对话框。
该怎么解决。

cordier 发表于 2008-7-10 15:44

自己搞定了。
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h> //再加这个头文件搞定。
main()
{
int count=0;
int word=0;
char input[200];   //指针改成数组就OK了
char text[200];    //指针改成数组就OK了。
FILE *fp;

fp=fopen("d:\\test.txt","r");
if (fp==NULL)
{
printf("File Open Error:\nPress any key to exit:");
getch();
exit(1);
}
printf("input a string for search:");
scanf("%s",input);

do
{
fscanf(fp,"%s",text);
word++;
if (strcmp(text,input)==0)
count++;
}while(!feof(fp));
printf("word=%d\nfind string:%s %d times\n",word,input,count);

getch();
}

cosdos 发表于 2008-7-10 18:38

楼主原来程序是完全不正确的,因为TC的检错能力太差所以才能通过的。

cosdos 发表于 2008-7-10 18:40

char *input;     未初始化
char *text;      未初始化


DOS下这样很有可能死机
Windows 最多程序挂掉

页: [1]

编程论坛