while ((c = getchar()) != EOF) Not terminating

前端 未结 8 1061
一个人的身影
一个人的身影 2020-12-02 01:54

I\'ve been reading \"The C Programming Language\" and I got to this part of inputs and outputs.

I\'ve read other threads saying that the console doesn\'t recognize e

8条回答
  •  清歌不尽
    2020-12-02 02:42

    while ((c = getchar()) != '\n'){
        if (c == ' ')
            ++nb;
        else if (c == '\n')
            ++nl;
        else if (c == '\t')
            ++nt;
    } 
    

    According to the condition in your while loop, you will not be able to count number of new lines because you will stop the while loop when the user inputs a new line character ('\n')

    Other than that, counting blanks and tabs just works fine.

    CTRL+Z will be recognized as a EOF in windows. But in order to recognize it in your program, use condition in while loop as ((c = getchar()) != EOF). Now when the user presses the key combination: CTRL+Z, It will input to console as EOF, and the program should recognize it as a character input.

    Doing this will allow you to count number of lines in the input

    So, my suggestion is:

    while ((c = getchar()) != EOF){
        if (c == ' ')
            ++nb;
        else if (c == '\n')
            ++nl;
        else if (c == '\t')
            ++nt;
    } 
    

提交回复
热议问题