-1

我创建了这个程序来计算单词和行数,但是当我输入一个只有 a 的文件时,\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;
}
4

1 回答 1

0

Here's a program that outputs only a single '\n' character.

#include <stdio.h>

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

I ran your code on a file that only contained a single '\n' and it output:

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

It seems that your test input file actually contains more characters than you think. On Windows platforms, it is common for lines of text to be terminated by the character sequence "\r\n" rather than only "\n". On that kind of input, your program prints:

john-schultzs-macbook-pro:~ jschultz$ ./a.out
Enter file name: input.txt
1         1
于 2015-02-19T00:47:42.210 回答