[英]reading characters from a file using c code
我写了一个C代码来计算文件中没有字符,单词和行数。
代码如下。
#include "stdio.h"
#include "conio.h"
#define FILE_NAME "abc.txt"
void main()
{
FILE *fr;
int noc = 0;
int now = 0;
int nol = 0;
char ch;
printf("hello world\n");
getch();
//clrscr();
fr = fopen("..\\abc.txt","r");
if(fr == NULL)
{
printf("\n error \n");
getch();
return;
}
ch = fgetc(fr);
while(ch != EOF)
{
printf("%c", ch);
noc++;
if(ch == ' ');
{
now++;
}
if(ch=='\n')
{
nol++;
now++;
}
ch=fgetc(fr);
}
fclose(fr);
printf("\n noc = %d now = %d nol = %d\n", noc, now, nol);
getch();
}
我的文件abc.txt如下。
Hello my friend.
How are you doing?
我得到以下输出:
hello world
Hello my friend.
How are you doing?
noc = 38 now = 40 nol = 2
该代码能够正确读取任何字符和行。 但是,它将每个字符视为一个单词。 当不计算上面代码中的单词数时,我不明白我在哪里出错。
详细的解释将不胜感激。
提前致谢。
if(ch == ' '); <------- see this (remove semicolon)
{
now++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.