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

前端 未结 8 989
一个人的身影
一个人的身影 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:48
        /* This program will calculate the number of blanks, tabs and new line in a text stream */
    
    #include <stdio.h>
    
    main () 
    {
        int c,nl = 0, blank = 0, tab = 0; //Newline, blanks and tabs.
        while ((c = getchar()) != EOF) {
            if (c == '\n')
                ++nl;
            else if (c == '\t')
                ++tab;
            else if (c == ' ')
                ++blank;
    }
        printf("Tabs = %d\nBlanks = %d\nNewLine = %d",tab, blank, nl);
    }
    

    I wrote this following code and it works properly on Ubuntu. As it is similar to what you wrote, I tried the code and Ctrl-D is working properly in UNIX.

    I tested the following code and have realized that if we input \n in text stream it will not increase the counter of the new line, same goes for a \t tab. Only pressing enter for new line and pressing tab for tab is counted by the counter this is a point to be noted.

    This is happening because pressing enter actually puts a newline character which is a single character whereas entering \n is treated as differently and they are actually two characters.

    I thought this will add value to this question so I explained this thing too. Thanks.

    0 讨论(0)
  • 2020-12-02 02:50
    while ((c = getchar())  !=EOF) {
    
    
    }
    

    Then use Ctrl+Z or F6 on Windows

    Following will wait for either a \n or EOF, which comes first

    while((c = getchar()) != '\n' && c != EOF){
    
    }
    
    0 讨论(0)
提交回复
热议问题