【问题标题】:C program to count lines and words in a file gives wrong word outputC程序计算文件中的行数和字数给出错误的字输出
【发布时间】:2015-02-19 00:16:35
【问题描述】:

我创建了这个程序来计算单词和行数,但是当我输入一个只有\n 的文件时,它说有一个单词不是我想要的。有什么想法吗?

#include <stdio.h> 

int main() 
{
    FILE *file; 
    char word[1000];        
    int c;
    int NumLines = 0; 
    int NumWords = 0;
    int was_space = 1;        

    printf("Enter file name: ");
    scanf("%s", word);
    file = fopen(word, "r");
    while ((c=fgetc(file)) !=EOF) {
        if (c == '\n') {
            NumLines++;
            if (was_space == 0) {
                NumWords++;
                was_space = 1;
            }
            was_space = 1;
        }
        else if ((c == '\t' || c == '-' || c == ':' || c== ' ') && was_space == 0) {
            NumWords++;
            was_space = 1;
        }
        else if (c != '\n' && c != '\t' && c != '-' && c != ':' && c != ' ') {
           was_space = 0;
           continue;
        }
        else if (was_space == 1)
           continue;
    }
    printf("%d %9d\n", NumLines, NumWords);
    fclose(file);

    return;
}

【问题讨论】:

  • 您确定文件中没有两个\n
  • 你的调试告诉你什么?
  • 调试的一般技巧:确保程序得到的和你认为得到的是一样的。一个简单的 printf("%c", c);在你的循环顶部将显示你的程序得到什么作为输入。
  • 第二个else if,你知道ch不能是'\n'。您应该错误检查来自fopen() 的返回值;人们经常拼错文件名。
  • 包括char 阅读和打印的计数。 while ((c=fgetc(file)) !=EOF) { count++; 怀疑将 > 1。

标签: c word-count line-count


【解决方案1】:

这是一个只输出一个 '\n' 字符的程序。

#include <stdio.h>

int main() { printf("\n"); return 0; }

我在一个只包含一个“\n”的文件上运行了你的代码,它输出:

john-schultzs-macbook-pro:~ jschultz$ ./output_newline > input.txt
john-schultzs-macbook-pro:~ jschultz$ wc input.txt
       1       0       1 input.txt
john-schultzs-macbook-pro:~ jschultz$ cat input.txt

john-schultzs-macbook-pro:~ jschultz$ ./a.out
Enter file name: input.txt
1         0

看来您的测试输入文件实际上包含的字符比您想象的要多。在 Windows 平台上,文本行通常由字符序列“\r\n”终止,而不仅仅是“\n”。在这种输入上,您的程序会打印:

john-schultzs-macbook-pro:~ jschultz$ ./a.out
Enter file name: input.txt
1         1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多