While loop in C don't break even after encountering a NULL character - c

here is the code to add the numbers present in an Alphanumeric string :
#include<stdio.h>
#include<stdlib.h>
int main()
{
int total=0;
char ch;
printf("enter the string\n");
ch=getchar();
while(ch!='\0')
{
printf("I am here !!");
if (!(isalpha(ch)))
total+=(int)ch;
ch=(char)getchar();
printf("I am here !!");
}
printf("\ntotal is %d",total);
return 0;
}
No matter what characters I input , it gives 4 " I am here " for each character.
I tried to use
while((ch=getchar())!='\0');
but it gives the same problem .

getchar does not return '\0' at the end of the input: it is not reading from a null-terminated C string, but from a console, file, or some other stream.
When no additional input is available, getchar returns EOF. That is the condition you should be checking to decide when to stop your loop.
Stack Overflow offers many good examples of how to implement a loop reading getchar (link#1; link#2; please note the data types used in the examples).

The reason it doesn't work is because '\0' cannot be inserted from the keyboard, so getchar() is unlikely to be able to return '\0', a correct way of testing for the end of input would be
int ch;
while (((ch = getchar()) != EOF) && (ch != '\n'))
This is because EOF means, that the user intentionally wanted to stop entering data, and '\n' is usually the last thing that will be seen when stdin is flushed, since it triggers the flushing.

Related

Undefined behaviour of scanf() in a do-while loop

I'm currently learning C by a book "C Programming a modern approach" and encountered this code. When I tried to run it, after typing consecutive characters like 'abc' and hitting Enter (new line), nothing was printed. Please explain what is going on here.
char ch;
do {
scanf("%c" , &ch);
} while (ch != '\n');
printf("%c", ch);
You're asking the user to input a character using scanf. This is happening in a loop until the user inputs a '\n' or newline character (the same as pressing the enter key), which is when the loop will break.
Your print statement will then print the character in the variable ch, which at that point will be '\n' (since this variable just stores one character, the last one you typed).
This newline character will probably be invisible when you run your program so you may not be seeing it. You can add another print statement after the loop and if that print statement starts at a newline, you know that the '\n' was printed on the previous line.
Something like:
#include <stdio.h>
int main()
{
char ch;
do
{
scanf("%c" , &ch);
} while (ch != '\n');
printf("%c", ch);
printf("I should show up on a newline");
return 0;
}
The code you provided reads characters from the input using the scanf() function and stores them in the variable ch until a newline character (\n) is encountered. After that, the program prints the last character that was read, which is the newline character.
The reason you are not seeing any output when you enter characters followed by a newline character is because the printf() statement is only executed after the loop has finished running. So, the program is waiting for you to enter a newline character to terminate the loop and print the last character that was read.
If you want to see the characters you enter, you can add a printf() statement inside the loop, like this:
char ch;
do {
scanf("%c" , &ch);
printf("%c", ch);
} while (ch != '\n');
This will print out each character as it is read from the input, so you can see what you're typing. Happy coding :)
When I tried to run it, after typing consecutive characters like abc and hitting Enter (new line), nothing was printed.
Well with the posted code, if the loop even finishes, the last byte read by scanf("%c", &ch) and stored into ch is the newline character. Hence printf("%c", ch) outputs this newline and it seems nothing is printed but something is, the newline which is invisible on the terminal but does move the cursor to the next line.
You can make this more explicit by changing the printf call to this:
printf("last value: '%c'\n", ch);
Note however that the posted code is not a recommended way to read the contents of the input stream:
scanf("%c", &ch) may fail to read a byte if the stream is at end of file. Failure to test this condition leads to undefined behavior (ch is unmodified, hence stays uninitialized if the input stream is an empty file) or to an infinite loop as ch may never receive a newline.
this code is a typical example of a do / while with a classic bug. It would be much better to write the code using getchar() and a while loop.
Here is a modified version:
#include <stdio.h>
int main(void) {
int c; // must use int to distinguish EOF from all valid byte values
int count = 0; // to tell whether a byte was read at all
char ch = 0; // the last byte read
// read all bytes from the input stream until end of file or a newline
while ((c = getchar()) != EOF && c != '\n') {
ch = (char)c;
count++;
}
if (count == 0) {
printf("no characters entered: ");
if (c == EOF) {
printf("end of file or read error\n");
} else {
printf("empty line\n");
}
} else {
printf("last character on line is '%c'\n", ch);
if (c == EOF) {
printf("end of file or input error encountered\n");
}
}
return 0;
}

Effectivelly flushing input stream in C [duplicate]

I have the following program:
int main(int argc, char *argv[])
{
char ch1, ch2;
printf("Input the first character:"); // Line 1
scanf("%c", &ch1);
printf("Input the second character:"); // Line 2
ch2 = getchar();
printf("ch1=%c, ASCII code = %d\n", ch1, ch1);
printf("ch2=%c, ASCII code = %d\n", ch2, ch2);
system("PAUSE");
return 0;
}
As the author of the above code have explained:
The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.
OK, I got this. But my first question is: Why the second getchar() (ch2 = getchar();) does not read the Enter key (13), rather than \n character?
Next, the author proposed 2 ways to solve such probrems:
use fflush()
write a function like this:
void
clear (void)
{
while ( getchar() != '\n' );
}
This code worked actually. But I cannot explain myself how it works? Because in the while statement, we use getchar() != '\n', that means read any single character except '\n'? if so, in the input buffer still remains the '\n' character?
The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.
The behavior you see at line 2 is correct, but that's not quite the correct explanation. With text-mode streams, it doesn't matter what line-endings your platform uses (whether carriage return (0x0D) + linefeed (0x0A), a bare CR, or a bare LF). The C runtime library will take care of that for you: your program will see just '\n' for newlines.
If you typed a character and pressed enter, then that input character would be read by line 1, and then '\n' would be read by line 2. See I'm using scanf %c to read a Y/N response, but later input gets skipped. from the comp.lang.c FAQ.
As for the proposed solutions, see (again from the comp.lang.c FAQ):
How can I flush pending input so that a user's typeahead isn't read at the next prompt? Will fflush(stdin) work?
If fflush won't work, what can I use to flush input?
which basically state that the only portable approach is to do:
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
Your getchar() != '\n' loop works because once you call getchar(), the returned character already has been removed from the input stream.
Also, I feel obligated to discourage you from using scanf entirely: Why does everyone say not to use scanf? What should I use instead?
You can do it (also) this way:
fseek(stdin,0,SEEK_END);
A portable way to clear up to the end of a line that you've already tried to read partially is:
int c;
while ( (c = getchar()) != '\n' && c != EOF ) { }
This reads and discards characters until it gets \n which signals the end of the file. It also checks against EOF in case the input stream gets closed before the end of the line. The type of c must be int (or larger) in order to be able to hold the value EOF.
There is no portable way to find out if there are any more lines after the current line (if there aren't, then getchar will block for input).
The lines:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF)
;
doesn't read only the characters before the linefeed ('\n'). It reads all the characters in the stream (and discards them) up to and including the next linefeed (or EOF is encountered). For the test to be true, it has to read the linefeed first; so when the loop stops, the linefeed was the last character read, but it has been read.
As for why it reads a linefeed instead of a carriage return, that's because the system has translated the return to a linefeed. When enter is pressed, that signals the end of the line... but the stream contains a line feed instead since that's the normal end-of-line marker for the system. That might be platform dependent.
Also, using fflush() on an input stream doesn't work on all platforms; for example it doesn't generally work on Linux.
But I cannot explain myself how it works? Because in the while statement, we use getchar() != '\n', that means read any single character except '\n'?? if so, in the input buffer still remains the '\n' character???
Am I misunderstanding something??
The thing you may not realize is that the comparison happens after getchar() removes the character from the input buffer. So when you reach the '\n', it is consumed and then you break out of the loop.
you can try
scanf("%c%*c", &ch1);
where %*c accepts and ignores the newline
one more method
instead of fflush(stdin) which invokes undefined behaviour you can write
while((getchar())!='\n');
don't forget the semicolon after while loop
scanf is a strange function, and there's a classic line from the movie WarGames that's relevant: "The only winning move is not to play".
If you find yourself needing to "flush input", you have already lost. The winning move is not to search desperately for some magic way to flush the nettlesome input: instead, what you need to do is to do input in some different (better) way, that doesn't involve leaving unread input on the input stream, and having it sit there and cause problems, such that you have to try to flush it instead.
There are basically three cases:
You are reading input using scanf, and it is leaving the user's newline on the input stream, and that stray newline is wrongly getting read by a later call to getchar or fgets. (This is the case you were initially asking about.)
You are reading input using scanf, and it is leaving the user's newline on the input stream, and that stray newline is wrongly getting read by a later call to scanf("%c").
You are reading numeric input using scanf, and the user is typing non-numeric text, and the non-numeric text is getting left on the input stream, meaning that the next call to scanf fails on it also.
In all three cases, it may seem like the right thing to do is to "flush" the offending input. And you can try, but it's cumbersome at best and impossible at worst. In the end I believe that trying to flush input is the wrong approach, and that there are better ways, depending on which case you were worried about:
In case 1, the better solution is, do not mix calls to scanf with other input functions. Either do all your input with scanf, or do all your input with getchar and/or fgets. To do all your input with scanf, you can replace calls to getchar with scanf("%c") — but see point 2. Theoretically you can replace calls to fgets with scanf("%[^\n]%*c"), although this has all sorts of further problems and I do not recommend it. To do all your input with fgets even though you wanted/needed some of scanf's parsing, you can read lines using fgets and then parse them after the fact using sscanf.
In case 2, the better solution is, never use scanf("%c"). Use scanf(" %c") instead. The magic extra space makes all the difference. (There's a long explanation of what that extra space does and why it helps, but it's beyond the scope of this answer.)
And in case 3, I'm afraid that there simply is no good solution. scanf has many problems, and one of its many problems is that its error handling is terrible. If you want to write a simple program that reads numeric input, and if you can assume that the user will always type proper numeric input when prompted to, then scanf("%d") can be an adequate — barely adequate — input method. But perhaps your goal is to do better. Perhaps you'd like to prompt the user for some numeric input, and check that the user did in fact enter numeric input, and if not, print an error message and ask the user to try again. In that case, I believe that for all intents and purposes you cannot meet this goal based around scanf. You can try, but it's like putting a onesie on a squirming baby: after getting both legs and one arm in, while you're trying to get the second arm in, one leg will have wriggled out. It is just far too much work to try to read and validate possibly-incorrect numeric input using scanf. It is far, far easier to do it some other way.
You will notice a theme running through all three cases I listed: they all began with "You are reading input using scanf...". There's a certain inescapable conclusion here. See this other question: What can I use for input conversion instead of scanf?
Now, I realize I still haven't answered the question you actually asked. When people ask, "How do I do X?", it can be really frustrating when all the answers are, "You shouldn't want to do X." If you really, really want to flush input, then besides the other answers people have given you here, two other good questions full of relevant answers are:
How to properly flush stdin in fgets loop
Using fflush(stdin)
I am surprised nobody mentioned this:
scanf("%*[^\n]");
How can I flush or clear the stdin input buffer in C?
The fflush() reference on the cppreference.com community wiki states (emphasis added):
For input streams (and for update streams on which the last operation was input), the behavior is undefined.
So, do not use fflush() on stdin.
If your goal of "flushing" stdin is to remove all chars sitting in the stdin buffer, then the best way to do it is manually with either getchar() or getc(stdin) (the same thing), or perhaps with read() (using stdin as the first argument) if using POSIX or Linux.
The most-upvoted answers here and here both do this with:
int c;
while ((c = getchar()) != '\n' && c != EOF);
I think a clearer (more-readable) way is to do it like this. My comments, of course, make my approach look much longer than it is:
/// Clear the stdin input stream by reading and discarding all incoming chars up
/// to and including the Enter key's newline ('\n') char. Once we hit the
/// newline char, stop calling `getc()`, as calls to `getc()` beyond that will
/// block again, waiting for more user input.
/// - I copied this function
/// from "eRCaGuy_hello_world/c/read_stdin_getc_until_only_enter_key.c".
void clear_stdin()
{
// keep reading 1 more char as long as the end of the stream, indicated by
// `EOF` (end of file), and the end of the line, indicated by the newline
// char inserted into the stream when you pressed Enter, have NOT been
// reached
while (true)
{
int c = getc(stdin);
if (c == EOF || c == '\n')
{
break;
}
}
}
I use this function in my two files here, for instance. See the context in these files for when clearing stdin might be most-useful:
array_2d_fill_from_user_input_scanf_and_getc.c
read_stdin_getc_until_only_enter_key.c
Note to self: I originally posted this answer here, but have since deleted that answer to leave this one as my only answer instead.
I encounter a problem trying to implement the solution
while ((c = getchar()) != '\n' && c != EOF) { }
I post a little adjustment 'Code B' for anyone who maybe have the same problem.
The problem was that the program kept me catching the '\n' character, independently from the enter character, here is the code that gave me the problem.
Code A
int y;
printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
continue;
}
printf("\n%c\n", toupper(y));
and the adjustment was to 'catch' the (n-1) character just before the conditional in the while loop be evaluated, here is the code:
Code B
int y, x;
printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
x = y;
}
printf("\n%c\n", toupper(x));
The possible explanation is that for the while loop to break, it has to assign the value '\n' to the variable y, so it will be the last assigned value.
If I missed something with the explanation, code A or code B please tell me, I’m barely new in c.
hope it helps someone
Try this:
stdin->_IO_read_ptr = stdin->_IO_read_end;
unsigned char a=0;
if(kbhit()){
a=getch();
while(kbhit())
getch();
}
cout<<hex<<(static_cast<unsigned int:->(a) & 0xFF)<<endl;
-or-
use maybe use _getch_nolock() ..???
Another solution not mentioned yet is to use:
rewind(stdin);
In brief. Putting the line...
while ((c = getchar()) != '\n') ;
...before the line reading the input is the only guaranteed method.
It uses only core C features ("conventional core of C language" as per K&R) which are guaranteed to work with all compilers in all circumstances.
In reality you may choose to add a prompt asking a user to hit ENTER to continue (or, optionally, hit Ctrl-D or any other button to finish or to perform other code):
printf("\nPress ENTER to continue, press CTRL-D when finished\n");
while ((c = getchar()) != '\n') {
if (c == EOF) {
printf("\nEnd of program, exiting now...\n");
return 0;
}
...
}
There is still a problem. A user can hit ENTER many times. This can be worked around by adding an input check to your input line:
while ((ch2 = getchar()) < 'a' || ch1 > 'Z') ;
Combination of the above two methods theoretically should be bulletproof.
In all other aspects the answer by #jamesdlin is the most comprehensive.
Quick solution is to add a 2nd scanf so that it forces ch2 to temporarily eat the carriage return. Doesn't do any checking so it assumes the user will play nice. Not exactly clearing the input buffer but it works just fine.
int main(int argc, char *argv[])
{
char ch1, ch2;
printf("Input the first character:"); // Line 1
scanf("%c", &ch1);
scanf("%c", &ch2); // This eats '\n' and allows you to enter your input
printf("Input the second character:"); // Line 2
ch2 = getchar();
printf("ch1=%c, ASCII code = %d\n", ch1, ch1);
printf("ch2=%c, ASCII code = %d\n", ch2, ch2);
system("PAUSE");
return 0;
}
I have written a function (and tested it too) which gets input from stdin and discards extra input (characters). This function is called get_input_from_stdin_and_discard_extra_characters(char *str, int size) and it reads at max "size - 1" characters and appends a '\0' at the end.
The code is below:
/* read at most size - 1 characters. */
char *get_input_from_stdin_and_discard_extra_characters(char *str, int size)
{
char c = 0;
int num_chars_to_read = size - 1;
int i = 0;
if (!str)
return NULL;
if (num_chars_to_read <= 0)
return NULL;
for (i = 0; i < num_chars_to_read; i++) {
c = getchar();
if ((c == '\n') || (c == EOF)) {
str[i] = 0;
return str;
}
str[i] = c;
} // end of for loop
str[i] = 0;
// discard rest of input
while ((c = getchar()) && (c != '\n') && (c != EOF));
return str;
} // end of get_input_from_stdin_and_discard_extra_characters
Just for completeness, in your case if you actually want to use scanf which there are plenty of reasons not to, I would add a space in front of the format specifier, telling scanf to ignore all whitespace in front of the character:
scanf(" %c", &ch1);
See more details here: https://en.cppreference.com/w/c/io/fscanf#Notes
Short, portable and declared in stdio.h
stdin = freopen(NULL,"r",stdin);
Doesn't get hung in an infinite loop when there is nothing on stdin to flush like the following well know line:
while ((c = getchar()) != '\n' && c != EOF) { }
A little expensive so don't use it in a program that needs to repeatedly clear the buffer.
Stole from a coworker :)

Don't know how to use getchar function correctly / C

I wanted to create a function that inputs a character in the console but the problem is that sometimes when I input 'a' it is considered as an empty char and the programm asks me to re-input a char.
This is the function :
char readChar()
{
char character;
character = getchar();
character = toupper(character);
while(getchar() != '\n' && getchar() != '\0');
return character;
}
Converting a barrage of comments into an answer.
1. Note that getchar() returns an int, not a char. And your loop needs to take into account EOF more than a null byte, though it's probably OK to detect null bytes.
My best guess about the trouble is that sometimes you do scanf("%d", &i) or something similar, and then call this function — but scanf() doesn't read the newline, so your function reads a newline left over by previous I/O operations. But without an MCVE (Minimal, Complete, and Verifiable Example), we can't demonstrate that my hypothesis is accurate.
2. Also, your 'eat the rest of the line' loop should only call getchar() once on each iteration; you call it twice. One option would be to use:
int readChar(void)
{
int c;
while ((c = getchar()) != EOF && isspace(c))
;
if (c == EOF)
return EOF;
int junk;
while ((junk = getchar()) != '\n' && junk != EOF /* && junk != '\0' */)
;
return toupper(c);
}
This eats white space until it gets a non-white-space character, and then reads any junk characters up to the next newline. It would fix my hypothetical scenario. Beware EOF — take EOF into account always.
Based on reading the Q&A about scanf() not reading a newline, Voltini proposed a fix:
char readChar()
{
char character;
scanf(" %c", &character);
getchar(); //I just added this line
character = toupper(character);
return character;
}
3. That is often a good way to work. Note that it has still not dealt with EOF — you always have to worry about EOF. The getchar() after the scanf() will read the newline if the user typed a and newline, but not if they typed a-z and then newline. You have to decide what you want done with that – and a character gobbling loop is often a good idea instead of the single getchar() call:
int c;
while ((c = getchar()) != EOF && c != '\n')
;
And in response to a comment along the lines of:
Please explain the importance of handling EOF.
4. If you don't ask, you won't necessarily learn about it! Input and output (I/O) and especially input, is fraught. Users don't type what you told them to type; they add spaces before or after what you told them to type; you expect something short like good and they type supercalifragilisticexpialidocious. And sometimes things go wrong and there is no more data available to be read — the state known as EOF or "end of file".
5. In the function with char character; scanf(" %c", &character); and no check, if there is no input (the user types ^D on Unix or ^Z on Windows, or the data file ended), you have no idea what value is going to be in the variable — it is quasi-random (indeterminate), and using it invokes undefined behaviour. That's bad. Further, in the code from the question, you have this loop, which would never end if the user indicates EOF.
while (getchar() != '\n' && getchar() != '\0') // Should handle EOF!
;
6. And, to add to the complexity, if plain char is an unsigned type, assigning to character and testing for EOF will always fail, and if plain char is a signed type, you will detect EOF on a valid character (often ÿ — small latin letter y with diaeresis in Unicode and 8859-1 or 8859-15 code sets). That's why my code uses int c; for character input. So, as you can see (I hope), there are solid reasons why you have to pay attention to EOF at all times. It can occur when you don't expect it, but your code shouldn't go into an infinite loop because of that.
I'm not sure how and where to … implement this … in my code.
7. There are two parts to that. One is in the readChar() function, which needs to return an int and not a char (for the same reasons that getchar() returns an int and not a char), or which needs an alternative interface such as:
bool readChar(char *cp)
{
int c;
while ((c = getchar()) != EOF && isspace(c))
;
if (c == EOF)
return false;
*cp = toupper(c);
while ((c = getchar()) != '\n' && c != EOF /* && c != '\0' */)
;
return true;
}
so that you can call:
if (readChar(&character))
{
…process valid input…
}
else
{
…EOF or other major problems — abandon hope all ye who enter here…
}
With the function correctly detecting EOF, you then have your calling code to fix so that it handles an EOF (error indication) from readChar().
Note that empty loop bodies are indicated by a semicolon indented on a line on its own. This is the way K&R (Kernighan and Ritchie in The C Programming Language — 1988) wrote loops with empty bodies, so you find it widely used.
You will find over time that an awful lot of the code you write in C is for error handling.
Do not read potentially twice per loop as with while(getchar() != '\n' && getchar() != '\0'); #Jonathan Leffler
To read a single and first character from a line of user input:
A text stream is an ordered sequence of characters composed into lines, each line
consisting of zero or more characters plus a terminating new-line character. Whether the
last line requires a terminating new-line character is implementation-defined. C11dr §7.21.2 2
Use getchar(). It returns an int in the range of unsigned char or EOF.
Read the rest of the line.
Sample code, a bit like OP's.
int readChar_and_make_uppercase() {
int ch = getchar();
if (ch != '\n' && ch != EOF) {
// read rest of line and throw it away
int dummy;
while ((dummy = getchar()) != '\n' && dummy != EOF) {
;
}
}
return toupper(ch);
}
Apparently, I forgot to take care of the newline character stored in the buffer (correct me if I'm wrong).
char readChar()
{
char character;
scanf(" %c", &character);
getchar(); //I just added this line
character = toupper(character);
return character;
}

C flush buffer and get only one char [duplicate]

I have the following program:
int main(int argc, char *argv[])
{
char ch1, ch2;
printf("Input the first character:"); // Line 1
scanf("%c", &ch1);
printf("Input the second character:"); // Line 2
ch2 = getchar();
printf("ch1=%c, ASCII code = %d\n", ch1, ch1);
printf("ch2=%c, ASCII code = %d\n", ch2, ch2);
system("PAUSE");
return 0;
}
As the author of the above code have explained:
The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.
OK, I got this. But my first question is: Why the second getchar() (ch2 = getchar();) does not read the Enter key (13), rather than \n character?
Next, the author proposed 2 ways to solve such probrems:
use fflush()
write a function like this:
void
clear (void)
{
while ( getchar() != '\n' );
}
This code worked actually. But I cannot explain myself how it works? Because in the while statement, we use getchar() != '\n', that means read any single character except '\n'? if so, in the input buffer still remains the '\n' character?
The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.
The behavior you see at line 2 is correct, but that's not quite the correct explanation. With text-mode streams, it doesn't matter what line-endings your platform uses (whether carriage return (0x0D) + linefeed (0x0A), a bare CR, or a bare LF). The C runtime library will take care of that for you: your program will see just '\n' for newlines.
If you typed a character and pressed enter, then that input character would be read by line 1, and then '\n' would be read by line 2. See I'm using scanf %c to read a Y/N response, but later input gets skipped. from the comp.lang.c FAQ.
As for the proposed solutions, see (again from the comp.lang.c FAQ):
How can I flush pending input so that a user's typeahead isn't read at the next prompt? Will fflush(stdin) work?
If fflush won't work, what can I use to flush input?
which basically state that the only portable approach is to do:
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
Your getchar() != '\n' loop works because once you call getchar(), the returned character already has been removed from the input stream.
Also, I feel obligated to discourage you from using scanf entirely: Why does everyone say not to use scanf? What should I use instead?
You can do it (also) this way:
fseek(stdin,0,SEEK_END);
A portable way to clear up to the end of a line that you've already tried to read partially is:
int c;
while ( (c = getchar()) != '\n' && c != EOF ) { }
This reads and discards characters until it gets \n which signals the end of the file. It also checks against EOF in case the input stream gets closed before the end of the line. The type of c must be int (or larger) in order to be able to hold the value EOF.
There is no portable way to find out if there are any more lines after the current line (if there aren't, then getchar will block for input).
The lines:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF)
;
doesn't read only the characters before the linefeed ('\n'). It reads all the characters in the stream (and discards them) up to and including the next linefeed (or EOF is encountered). For the test to be true, it has to read the linefeed first; so when the loop stops, the linefeed was the last character read, but it has been read.
As for why it reads a linefeed instead of a carriage return, that's because the system has translated the return to a linefeed. When enter is pressed, that signals the end of the line... but the stream contains a line feed instead since that's the normal end-of-line marker for the system. That might be platform dependent.
Also, using fflush() on an input stream doesn't work on all platforms; for example it doesn't generally work on Linux.
But I cannot explain myself how it works? Because in the while statement, we use getchar() != '\n', that means read any single character except '\n'?? if so, in the input buffer still remains the '\n' character???
Am I misunderstanding something??
The thing you may not realize is that the comparison happens after getchar() removes the character from the input buffer. So when you reach the '\n', it is consumed and then you break out of the loop.
you can try
scanf("%c%*c", &ch1);
where %*c accepts and ignores the newline
one more method
instead of fflush(stdin) which invokes undefined behaviour you can write
while((getchar())!='\n');
don't forget the semicolon after while loop
scanf is a strange function, and there's a classic line from the movie WarGames that's relevant: "The only winning move is not to play".
If you find yourself needing to "flush input", you have already lost. The winning move is not to search desperately for some magic way to flush the nettlesome input: instead, what you need to do is to do input in some different (better) way, that doesn't involve leaving unread input on the input stream, and having it sit there and cause problems, such that you have to try to flush it instead.
There are basically three cases:
You are reading input using scanf, and it is leaving the user's newline on the input stream, and that stray newline is wrongly getting read by a later call to getchar or fgets. (This is the case you were initially asking about.)
You are reading input using scanf, and it is leaving the user's newline on the input stream, and that stray newline is wrongly getting read by a later call to scanf("%c").
You are reading numeric input using scanf, and the user is typing non-numeric text, and the non-numeric text is getting left on the input stream, meaning that the next call to scanf fails on it also.
In all three cases, it may seem like the right thing to do is to "flush" the offending input. And you can try, but it's cumbersome at best and impossible at worst. In the end I believe that trying to flush input is the wrong approach, and that there are better ways, depending on which case you were worried about:
In case 1, the better solution is, do not mix calls to scanf with other input functions. Either do all your input with scanf, or do all your input with getchar and/or fgets. To do all your input with scanf, you can replace calls to getchar with scanf("%c") — but see point 2. Theoretically you can replace calls to fgets with scanf("%[^\n]%*c"), although this has all sorts of further problems and I do not recommend it. To do all your input with fgets even though you wanted/needed some of scanf's parsing, you can read lines using fgets and then parse them after the fact using sscanf.
In case 2, the better solution is, never use scanf("%c"). Use scanf(" %c") instead. The magic extra space makes all the difference. (There's a long explanation of what that extra space does and why it helps, but it's beyond the scope of this answer.)
And in case 3, I'm afraid that there simply is no good solution. scanf has many problems, and one of its many problems is that its error handling is terrible. If you want to write a simple program that reads numeric input, and if you can assume that the user will always type proper numeric input when prompted to, then scanf("%d") can be an adequate — barely adequate — input method. But perhaps your goal is to do better. Perhaps you'd like to prompt the user for some numeric input, and check that the user did in fact enter numeric input, and if not, print an error message and ask the user to try again. In that case, I believe that for all intents and purposes you cannot meet this goal based around scanf. You can try, but it's like putting a onesie on a squirming baby: after getting both legs and one arm in, while you're trying to get the second arm in, one leg will have wriggled out. It is just far too much work to try to read and validate possibly-incorrect numeric input using scanf. It is far, far easier to do it some other way.
You will notice a theme running through all three cases I listed: they all began with "You are reading input using scanf...". There's a certain inescapable conclusion here. See this other question: What can I use for input conversion instead of scanf?
Now, I realize I still haven't answered the question you actually asked. When people ask, "How do I do X?", it can be really frustrating when all the answers are, "You shouldn't want to do X." If you really, really want to flush input, then besides the other answers people have given you here, two other good questions full of relevant answers are:
How to properly flush stdin in fgets loop
Using fflush(stdin)
I am surprised nobody mentioned this:
scanf("%*[^\n]");
How can I flush or clear the stdin input buffer in C?
The fflush() reference on the cppreference.com community wiki states (emphasis added):
For input streams (and for update streams on which the last operation was input), the behavior is undefined.
So, do not use fflush() on stdin.
If your goal of "flushing" stdin is to remove all chars sitting in the stdin buffer, then the best way to do it is manually with either getchar() or getc(stdin) (the same thing), or perhaps with read() (using stdin as the first argument) if using POSIX or Linux.
The most-upvoted answers here and here both do this with:
int c;
while ((c = getchar()) != '\n' && c != EOF);
I think a clearer (more-readable) way is to do it like this. My comments, of course, make my approach look much longer than it is:
/// Clear the stdin input stream by reading and discarding all incoming chars up
/// to and including the Enter key's newline ('\n') char. Once we hit the
/// newline char, stop calling `getc()`, as calls to `getc()` beyond that will
/// block again, waiting for more user input.
/// - I copied this function
/// from "eRCaGuy_hello_world/c/read_stdin_getc_until_only_enter_key.c".
void clear_stdin()
{
// keep reading 1 more char as long as the end of the stream, indicated by
// `EOF` (end of file), and the end of the line, indicated by the newline
// char inserted into the stream when you pressed Enter, have NOT been
// reached
while (true)
{
int c = getc(stdin);
if (c == EOF || c == '\n')
{
break;
}
}
}
I use this function in my two files here, for instance. See the context in these files for when clearing stdin might be most-useful:
array_2d_fill_from_user_input_scanf_and_getc.c
read_stdin_getc_until_only_enter_key.c
Note to self: I originally posted this answer here, but have since deleted that answer to leave this one as my only answer instead.
I encounter a problem trying to implement the solution
while ((c = getchar()) != '\n' && c != EOF) { }
I post a little adjustment 'Code B' for anyone who maybe have the same problem.
The problem was that the program kept me catching the '\n' character, independently from the enter character, here is the code that gave me the problem.
Code A
int y;
printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
continue;
}
printf("\n%c\n", toupper(y));
and the adjustment was to 'catch' the (n-1) character just before the conditional in the while loop be evaluated, here is the code:
Code B
int y, x;
printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
x = y;
}
printf("\n%c\n", toupper(x));
The possible explanation is that for the while loop to break, it has to assign the value '\n' to the variable y, so it will be the last assigned value.
If I missed something with the explanation, code A or code B please tell me, I’m barely new in c.
hope it helps someone
Try this:
stdin->_IO_read_ptr = stdin->_IO_read_end;
unsigned char a=0;
if(kbhit()){
a=getch();
while(kbhit())
getch();
}
cout<<hex<<(static_cast<unsigned int:->(a) & 0xFF)<<endl;
-or-
use maybe use _getch_nolock() ..???
Another solution not mentioned yet is to use:
rewind(stdin);
In brief. Putting the line...
while ((c = getchar()) != '\n') ;
...before the line reading the input is the only guaranteed method.
It uses only core C features ("conventional core of C language" as per K&R) which are guaranteed to work with all compilers in all circumstances.
In reality you may choose to add a prompt asking a user to hit ENTER to continue (or, optionally, hit Ctrl-D or any other button to finish or to perform other code):
printf("\nPress ENTER to continue, press CTRL-D when finished\n");
while ((c = getchar()) != '\n') {
if (c == EOF) {
printf("\nEnd of program, exiting now...\n");
return 0;
}
...
}
There is still a problem. A user can hit ENTER many times. This can be worked around by adding an input check to your input line:
while ((ch2 = getchar()) < 'a' || ch1 > 'Z') ;
Combination of the above two methods theoretically should be bulletproof.
In all other aspects the answer by #jamesdlin is the most comprehensive.
Quick solution is to add a 2nd scanf so that it forces ch2 to temporarily eat the carriage return. Doesn't do any checking so it assumes the user will play nice. Not exactly clearing the input buffer but it works just fine.
int main(int argc, char *argv[])
{
char ch1, ch2;
printf("Input the first character:"); // Line 1
scanf("%c", &ch1);
scanf("%c", &ch2); // This eats '\n' and allows you to enter your input
printf("Input the second character:"); // Line 2
ch2 = getchar();
printf("ch1=%c, ASCII code = %d\n", ch1, ch1);
printf("ch2=%c, ASCII code = %d\n", ch2, ch2);
system("PAUSE");
return 0;
}
I have written a function (and tested it too) which gets input from stdin and discards extra input (characters). This function is called get_input_from_stdin_and_discard_extra_characters(char *str, int size) and it reads at max "size - 1" characters and appends a '\0' at the end.
The code is below:
/* read at most size - 1 characters. */
char *get_input_from_stdin_and_discard_extra_characters(char *str, int size)
{
char c = 0;
int num_chars_to_read = size - 1;
int i = 0;
if (!str)
return NULL;
if (num_chars_to_read <= 0)
return NULL;
for (i = 0; i < num_chars_to_read; i++) {
c = getchar();
if ((c == '\n') || (c == EOF)) {
str[i] = 0;
return str;
}
str[i] = c;
} // end of for loop
str[i] = 0;
// discard rest of input
while ((c = getchar()) && (c != '\n') && (c != EOF));
return str;
} // end of get_input_from_stdin_and_discard_extra_characters
Just for completeness, in your case if you actually want to use scanf which there are plenty of reasons not to, I would add a space in front of the format specifier, telling scanf to ignore all whitespace in front of the character:
scanf(" %c", &ch1);
See more details here: https://en.cppreference.com/w/c/io/fscanf#Notes
Short, portable and declared in stdio.h
stdin = freopen(NULL,"r",stdin);
Doesn't get hung in an infinite loop when there is nothing on stdin to flush like the following well know line:
while ((c = getchar()) != '\n' && c != EOF) { }
A little expensive so don't use it in a program that needs to repeatedly clear the buffer.
Stole from a coworker :)

How to clear input buffer in C?

I have the following program:
int main(int argc, char *argv[])
{
char ch1, ch2;
printf("Input the first character:"); // Line 1
scanf("%c", &ch1);
printf("Input the second character:"); // Line 2
ch2 = getchar();
printf("ch1=%c, ASCII code = %d\n", ch1, ch1);
printf("ch2=%c, ASCII code = %d\n", ch2, ch2);
system("PAUSE");
return 0;
}
As the author of the above code have explained:
The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.
OK, I got this. But my first question is: Why the second getchar() (ch2 = getchar();) does not read the Enter key (13), rather than \n character?
Next, the author proposed 2 ways to solve such probrems:
use fflush()
write a function like this:
void
clear (void)
{
while ( getchar() != '\n' );
}
This code worked actually. But I cannot explain myself how it works? Because in the while statement, we use getchar() != '\n', that means read any single character except '\n'? if so, in the input buffer still remains the '\n' character?
The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.
The behavior you see at line 2 is correct, but that's not quite the correct explanation. With text-mode streams, it doesn't matter what line-endings your platform uses (whether carriage return (0x0D) + linefeed (0x0A), a bare CR, or a bare LF). The C runtime library will take care of that for you: your program will see just '\n' for newlines.
If you typed a character and pressed enter, then that input character would be read by line 1, and then '\n' would be read by line 2. See I'm using scanf %c to read a Y/N response, but later input gets skipped. from the comp.lang.c FAQ.
As for the proposed solutions, see (again from the comp.lang.c FAQ):
How can I flush pending input so that a user's typeahead isn't read at the next prompt? Will fflush(stdin) work?
If fflush won't work, what can I use to flush input?
which basically state that the only portable approach is to do:
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
Your getchar() != '\n' loop works because once you call getchar(), the returned character already has been removed from the input stream.
Also, I feel obligated to discourage you from using scanf entirely: Why does everyone say not to use scanf? What should I use instead?
You can do it (also) this way:
fseek(stdin,0,SEEK_END);
A portable way to clear up to the end of a line that you've already tried to read partially is:
int c;
while ( (c = getchar()) != '\n' && c != EOF ) { }
This reads and discards characters until it gets \n which signals the end of the file. It also checks against EOF in case the input stream gets closed before the end of the line. The type of c must be int (or larger) in order to be able to hold the value EOF.
There is no portable way to find out if there are any more lines after the current line (if there aren't, then getchar will block for input).
The lines:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF)
;
doesn't read only the characters before the linefeed ('\n'). It reads all the characters in the stream (and discards them) up to and including the next linefeed (or EOF is encountered). For the test to be true, it has to read the linefeed first; so when the loop stops, the linefeed was the last character read, but it has been read.
As for why it reads a linefeed instead of a carriage return, that's because the system has translated the return to a linefeed. When enter is pressed, that signals the end of the line... but the stream contains a line feed instead since that's the normal end-of-line marker for the system. That might be platform dependent.
Also, using fflush() on an input stream doesn't work on all platforms; for example it doesn't generally work on Linux.
But I cannot explain myself how it works? Because in the while statement, we use getchar() != '\n', that means read any single character except '\n'?? if so, in the input buffer still remains the '\n' character???
Am I misunderstanding something??
The thing you may not realize is that the comparison happens after getchar() removes the character from the input buffer. So when you reach the '\n', it is consumed and then you break out of the loop.
you can try
scanf("%c%*c", &ch1);
where %*c accepts and ignores the newline
one more method
instead of fflush(stdin) which invokes undefined behaviour you can write
while((getchar())!='\n');
don't forget the semicolon after while loop
scanf is a strange function, and there's a classic line from the movie WarGames that's relevant: "The only winning move is not to play".
If you find yourself needing to "flush input", you have already lost. The winning move is not to search desperately for some magic way to flush the nettlesome input: instead, what you need to do is to do input in some different (better) way, that doesn't involve leaving unread input on the input stream, and having it sit there and cause problems, such that you have to try to flush it instead.
There are basically three cases:
You are reading input using scanf, and it is leaving the user's newline on the input stream, and that stray newline is wrongly getting read by a later call to getchar or fgets. (This is the case you were initially asking about.)
You are reading input using scanf, and it is leaving the user's newline on the input stream, and that stray newline is wrongly getting read by a later call to scanf("%c").
You are reading numeric input using scanf, and the user is typing non-numeric text, and the non-numeric text is getting left on the input stream, meaning that the next call to scanf fails on it also.
In all three cases, it may seem like the right thing to do is to "flush" the offending input. And you can try, but it's cumbersome at best and impossible at worst. In the end I believe that trying to flush input is the wrong approach, and that there are better ways, depending on which case you were worried about:
In case 1, the better solution is, do not mix calls to scanf with other input functions. Either do all your input with scanf, or do all your input with getchar and/or fgets. To do all your input with scanf, you can replace calls to getchar with scanf("%c") — but see point 2. Theoretically you can replace calls to fgets with scanf("%[^\n]%*c"), although this has all sorts of further problems and I do not recommend it. To do all your input with fgets even though you wanted/needed some of scanf's parsing, you can read lines using fgets and then parse them after the fact using sscanf.
In case 2, the better solution is, never use scanf("%c"). Use scanf(" %c") instead. The magic extra space makes all the difference. (There's a long explanation of what that extra space does and why it helps, but it's beyond the scope of this answer.)
And in case 3, I'm afraid that there simply is no good solution. scanf has many problems, and one of its many problems is that its error handling is terrible. If you want to write a simple program that reads numeric input, and if you can assume that the user will always type proper numeric input when prompted to, then scanf("%d") can be an adequate — barely adequate — input method. But perhaps your goal is to do better. Perhaps you'd like to prompt the user for some numeric input, and check that the user did in fact enter numeric input, and if not, print an error message and ask the user to try again. In that case, I believe that for all intents and purposes you cannot meet this goal based around scanf. You can try, but it's like putting a onesie on a squirming baby: after getting both legs and one arm in, while you're trying to get the second arm in, one leg will have wriggled out. It is just far too much work to try to read and validate possibly-incorrect numeric input using scanf. It is far, far easier to do it some other way.
You will notice a theme running through all three cases I listed: they all began with "You are reading input using scanf...". There's a certain inescapable conclusion here. See this other question: What can I use for input conversion instead of scanf?
Now, I realize I still haven't answered the question you actually asked. When people ask, "How do I do X?", it can be really frustrating when all the answers are, "You shouldn't want to do X." If you really, really want to flush input, then besides the other answers people have given you here, two other good questions full of relevant answers are:
How to properly flush stdin in fgets loop
Using fflush(stdin)
I am surprised nobody mentioned this:
scanf("%*[^\n]");
How can I flush or clear the stdin input buffer in C?
The fflush() reference on the cppreference.com community wiki states (emphasis added):
For input streams (and for update streams on which the last operation was input), the behavior is undefined.
So, do not use fflush() on stdin.
If your goal of "flushing" stdin is to remove all chars sitting in the stdin buffer, then the best way to do it is manually with either getchar() or getc(stdin) (the same thing), or perhaps with read() (using stdin as the first argument) if using POSIX or Linux.
The most-upvoted answers here and here both do this with:
int c;
while ((c = getchar()) != '\n' && c != EOF);
I think a clearer (more-readable) way is to do it like this. My comments, of course, make my approach look much longer than it is:
/// Clear the stdin input stream by reading and discarding all incoming chars up
/// to and including the Enter key's newline ('\n') char. Once we hit the
/// newline char, stop calling `getc()`, as calls to `getc()` beyond that will
/// block again, waiting for more user input.
/// - I copied this function
/// from "eRCaGuy_hello_world/c/read_stdin_getc_until_only_enter_key.c".
void clear_stdin()
{
// keep reading 1 more char as long as the end of the stream, indicated by
// `EOF` (end of file), and the end of the line, indicated by the newline
// char inserted into the stream when you pressed Enter, have NOT been
// reached
while (true)
{
int c = getc(stdin);
if (c == EOF || c == '\n')
{
break;
}
}
}
I use this function in my two files here, for instance. See the context in these files for when clearing stdin might be most-useful:
array_2d_fill_from_user_input_scanf_and_getc.c
read_stdin_getc_until_only_enter_key.c
Note to self: I originally posted this answer here, but have since deleted that answer to leave this one as my only answer instead.
I encounter a problem trying to implement the solution
while ((c = getchar()) != '\n' && c != EOF) { }
I post a little adjustment 'Code B' for anyone who maybe have the same problem.
The problem was that the program kept me catching the '\n' character, independently from the enter character, here is the code that gave me the problem.
Code A
int y;
printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
continue;
}
printf("\n%c\n", toupper(y));
and the adjustment was to 'catch' the (n-1) character just before the conditional in the while loop be evaluated, here is the code:
Code B
int y, x;
printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
x = y;
}
printf("\n%c\n", toupper(x));
The possible explanation is that for the while loop to break, it has to assign the value '\n' to the variable y, so it will be the last assigned value.
If I missed something with the explanation, code A or code B please tell me, I’m barely new in c.
hope it helps someone
Try this:
stdin->_IO_read_ptr = stdin->_IO_read_end;
unsigned char a=0;
if(kbhit()){
a=getch();
while(kbhit())
getch();
}
cout<<hex<<(static_cast<unsigned int:->(a) & 0xFF)<<endl;
-or-
use maybe use _getch_nolock() ..???
Another solution not mentioned yet is to use:
rewind(stdin);
In brief. Putting the line...
while ((c = getchar()) != '\n') ;
...before the line reading the input is the only guaranteed method.
It uses only core C features ("conventional core of C language" as per K&R) which are guaranteed to work with all compilers in all circumstances.
In reality you may choose to add a prompt asking a user to hit ENTER to continue (or, optionally, hit Ctrl-D or any other button to finish or to perform other code):
printf("\nPress ENTER to continue, press CTRL-D when finished\n");
while ((c = getchar()) != '\n') {
if (c == EOF) {
printf("\nEnd of program, exiting now...\n");
return 0;
}
...
}
There is still a problem. A user can hit ENTER many times. This can be worked around by adding an input check to your input line:
while ((ch2 = getchar()) < 'a' || ch1 > 'Z') ;
Combination of the above two methods theoretically should be bulletproof.
In all other aspects the answer by #jamesdlin is the most comprehensive.
Quick solution is to add a 2nd scanf so that it forces ch2 to temporarily eat the carriage return. Doesn't do any checking so it assumes the user will play nice. Not exactly clearing the input buffer but it works just fine.
int main(int argc, char *argv[])
{
char ch1, ch2;
printf("Input the first character:"); // Line 1
scanf("%c", &ch1);
scanf("%c", &ch2); // This eats '\n' and allows you to enter your input
printf("Input the second character:"); // Line 2
ch2 = getchar();
printf("ch1=%c, ASCII code = %d\n", ch1, ch1);
printf("ch2=%c, ASCII code = %d\n", ch2, ch2);
system("PAUSE");
return 0;
}
I have written a function (and tested it too) which gets input from stdin and discards extra input (characters). This function is called get_input_from_stdin_and_discard_extra_characters(char *str, int size) and it reads at max "size - 1" characters and appends a '\0' at the end.
The code is below:
/* read at most size - 1 characters. */
char *get_input_from_stdin_and_discard_extra_characters(char *str, int size)
{
char c = 0;
int num_chars_to_read = size - 1;
int i = 0;
if (!str)
return NULL;
if (num_chars_to_read <= 0)
return NULL;
for (i = 0; i < num_chars_to_read; i++) {
c = getchar();
if ((c == '\n') || (c == EOF)) {
str[i] = 0;
return str;
}
str[i] = c;
} // end of for loop
str[i] = 0;
// discard rest of input
while ((c = getchar()) && (c != '\n') && (c != EOF));
return str;
} // end of get_input_from_stdin_and_discard_extra_characters
Just for completeness, in your case if you actually want to use scanf which there are plenty of reasons not to, I would add a space in front of the format specifier, telling scanf to ignore all whitespace in front of the character:
scanf(" %c", &ch1);
See more details here: https://en.cppreference.com/w/c/io/fscanf#Notes
Short, portable and declared in stdio.h
stdin = freopen(NULL,"r",stdin);
Doesn't get hung in an infinite loop when there is nothing on stdin to flush like the following well know line:
while ((c = getchar()) != '\n' && c != EOF) { }
A little expensive so don't use it in a program that needs to repeatedly clear the buffer.
Stole from a coworker :)

Resources