c - 匹配文件中每个单词的列和行

标签 c

我无法正确计算行数!

我的文件例如是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/

相关文章:

Java : When does corresponding memory come into existence for local variables?

objective-c - Robbiehanson 在 xmpp 框架中的内存泄漏

c - 如何编写一个使用GCC编译其他C程序的C程序?

c - 有了#define 值替换列表,如何将值解析为标识符的字符串?

c - 在 C 中将数据复制到空字符串时出现意外截断

c - 使用 makefile 链接 C 程序时出错

c - 如何在 C 中扫描特定的字符串格式?

c - 如何从 UnsafeMutableRawPointer 获取页对齐地址?

c - c全局变量使用中的键盘中断句柄

c - 提升指向未定义位置的指针是否合法?