How to flush the stdin??
Why is it not working in the following code snippet?
#include
#include
#i
You can't clean stdin in Linux without bumping into scenarios that the command will start waiting for input in some cases. The way to solve it is to replace all std::cin with readLineToStdString():
void readLine(char* input , int nMaxLenIncludingTerminatingNull )
{
fgets(input, nMaxLenIncludingTerminatingNull , stdin);
int nLen = strlen(input);
if ( input[nLen-1] == '\n' )
input[nLen-1] = '\0';
}
std::string readLineToStdString(int nMaxLenIncludingTerminatingNull)
{
if ( nMaxLenIncludingTerminatingNull <= 0 )
return "";
char* input = new char[nMaxLenIncludingTerminatingNull];
readLine(input , nMaxLenIncludingTerminatingNull );
string sResult = input;
delete[] input;
input = NULL;
return sResult;
}
This will also allow you to enter spaces in std::cin string.
int c;
while((c = getchar()) != '\n' && c != EOF);
Is how I'd clear the input buffer.
From the comp.lang.c FAQ, see:
You are overriding the last element of the input in arg
with '\0'
. That line should be arg[i]='\0';
instead (after error and boundary checking you are missing.)
Other's already commented of the flushing part.
In Windows you can use rewind(stdin) fuction.
How to flush the stdin??
Flushing input streams is invoking Undefined Behavior. Don't try it.
You can only flush output streams.