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
First of all press Ctrl + Z which will print ^Z then press Enter to go to EOF..
Change the line
// Buggy, you want calculate the # of '\n' in loop body,
// so logically you shouldn't use it as a stop condition.
while ((c = getchar()) != '\n')
to
while ((c = getchar()) != EOF)
And try press Ctrl + C
in your console window on Windows. It works on my platform which is running Win7.
On Windows, you type Ctrl-Z on a line by itself (no spaces or anything) and type the Return after that. On Windows, you could technically skip the EOF indicator and keep reading characters, though this doesn't apply to other operating systems because EOF actually means EOF.
If you are on unix system:
The only way to simulate EOF via keyboard while feeding input to the program manually is to press CTRL+D
Here are a couple methods of feeding input to your program and be able to signal EOF at the end of the input:
./myprog <<< "Here is a string to work with"
./myprog < input.file
Any of the above listed methods will work with the following code:
#include <stdio.h>
#ifndef EOF
#define EOF (-1)
#endif
int main(void)
{
int nb, nl, nt, c;
nb = 0;
nl = 0;
nt = 0;
while ((c = getchar()) != EOF){
if (c == ' ')
++nb;
else if (c == '\n')
++nl;
else if (c == '\t')
++nt;
}
printf("Input has %d blanks, %d tabs, and %d newlines\n", nb, nt, nl);
return 0;
}
Not sure if the here-string format for unix is available for windows, but input redirection should be similar
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;
}
To recognize EOF in Turbo C++, in the terminal window press Ctrl+z; this will act as EOF in the program and then terminate the program....with the condition:
while ((c = getchar()) != EOF)