I'm making a simple program in C that reads an input. It then displays the number of characters used.
What I tried first:
#include <stdio.h>
int main(int argc, char** argv) {
int currentChar;
int charCount = 0;
while((currentChar = getchar()) != EOF) {
charCount++;
}
printf("Display char count? [y/n]");
int response = getchar();
if(response == 'y' || response == 'Y')
printf("Count: %d\n",charCount);
}
What happened:
I would enter some lines and end it with ^D
(I'm on Mac). The program would not wait at int response = getchar();
. I found online that this is because there is still content left in the input stream.
My first question is what content would that be? I don't enter anything after pressing ^D
to input EOF
and when I tried to print anything left in the stream, it would print a ?
.
What I tried next:
Assuming there were characters left in the input stream, I made a function to clear the input buffer:
void clearInputBuffer() {
while(getchar() != '\n') {};
}
I called the function right after the while loop:
while((currentChar = getchar()) != EOF) {
charCount++;
}
clearInputBuffer();
Now I would assume if there is anything left after pressing ^D
, it would be cleared up to the next \n
.
But instead, I can't stop the input request. When I press ^D
, rather than sending EOF
to currentChar
, a ^D
is shown on the terminal.
I know there is a probably a solution to this online, but since I'm not sure what exactly my problem is, I don't really know what to look for.
Why is this happening? Can someone also explain exactly what is going on behind the scenes of this program and the Terminal?
Aucun commentaire:
Enregistrer un commentaire