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, I tried doing the same in an online compiler and ctrl D worked.
CodePudding user response:
Since letters are not being counted, a letter could be used to exit the loop.
This uses a lower case x
.
#include <stdio.h>
int main ( void) {
int c = 0;
int newLines = 0;
int tabs = 0;
int blanks = 0;
while ((c = getchar()) != EOF && c != 'x'){
if (c == '\n'){
newLines;
} else if(c == '\t'){
tabs;
} else if(c == ' '){
blanks;
}
}
printf("New Lines = %d , Tabs = %d , Blanks == %d\n", newLines, tabs, blanks);
return 0;
}
CodePudding user response:
to get EOF you need to press Ctrl z on windows platfrom at the end of your string input from console.