1

Exercise 1-8 in C by Kernighan and Ritchie

void countBlanksTabsNewlines() {
    int c, newLines, tabs, blanks;
    newLines = 0;
    tabs = 0;
    blanks = 0;

    while ((c = getchar()) != EOF){
        if (c == '\n'){
            ++newLines;
        } else if(c == '\t'){
            ++tabs;
        } else if(c == ' '){
            ++blanks;
        }
    }
    printf("New Lines = %d , Tabs = %d , Blanks == %d", newLines, tabs, blanks);
}

When I use any input then press enter, the while loop doesn't terminate. My code is based off the example counting just new lines from the book, so not sure how to solve. Thanks :)

Edit: I failed to mention I am using CLion IDE and after trying the shortcuts suggested here in CLion (unsuccessfully), I tried doing the same in an online compiler and ctrl+D worked.

TaxFrog
  • 11
  • 2
  • 3
    In Windows, the Ctrl-Z must be between two newline keypresses. – Weather Vane Jul 15 '22 at 09:28
  • 1
    Are you referring to the 1988 second edition of the book? In which case I hate to tell you that the book is now very outdated and should not be used as a resource for learning C. – Dai Jul 15 '22 at 09:28
  • 3
    'Enter' is not EOF. – Weather Vane Jul 15 '22 at 09:29
  • @Dai Yeah I'm using that exact version (signed by both Kernighan and Ritchie, praise second hand books lol), it is the recommended text for my next year in university so I'm going to stick with it. Regardless, what text is more up to date and worth using? – TaxFrog Jul 15 '22 at 10:24
  • @TaxFrog _"it is the recommended text for my next year in university"_ - uh-oh... you might want to ask your dean/prof _why_ it's on the list (that said, my own uni had the book on the reading list too, but only as a historical reference). Anyway, [check out this QA](https://stackoverflow.com/q/562303/159145) - and ensure any book you get covers C17 and ideally draft C23 too. – Dai Jul 15 '22 at 10:34
  • @TaxFrog, Aside: Rather than declare and later assign, declare and initialize in the same line: `int blanks; ... blanks = 0;` --> `int blanks = 0;`. – chux - Reinstate Monica Jul 15 '22 at 13:15
  • @TaxFrog this issue relates to your environment. Tag CLion added. – chux - Reinstate Monica Jul 15 '22 at 13:18

1 Answers1

-2

to get EOF you need to press Ctrl+z on windows platfrom at the end of your string input from console.