我无法正确计算行数!
我的文件例如是a1.txt
:
Words are flowing out \n
like \n
They \n
Pools dsa\n
Possessing
我的代码:
int main()
{
FILE * file2;
file2 = fopen("a1.txt","r");
int c ;
unsigned long newline_count =1,sthlh_count=0;
char str[56];
while (fscanf(file2,"%s",str)!=EOF)
{
c=fgetc(file2);
printf("%s\n",str);
if ( c == '\n' ) newline_count++;
if ( c == ' ' ) sthlh_count++;
printf("%d %d\n",newline_count,sthlh_count);
}
}
最佳答案
我不确定您的问题到底是什么,但我立即看到一件事。
while (fscanf(file2,"%s",str)!=EOF)
在 while 循环体中,您永远不会使用 str
的值来保存 printf
。请记住,fscanf 不仅读取文件,还移动文件对象中的指针,该指针告诉运行时您在文件中的位置,因此读入 str 的所有字符都不会被循环体中的代码。这就是为什么你会“掉线”。
这是你应该做的:
while ( (c=fgetc(file2)) != EOF ) ...
在这里,您只是读取每个字符,将其存储在 c
中,然后检查它是否为 EOF
。另外,如果您仍然希望 printf 工作,只需在循环体中打印出该字符,而不是打印该行。删除其他 fgetc 行(否则您将“丢失”字符!)。
关于c - 匹配文件中每个单词的列和行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24966057/