Issue is related only to Windows. I am using visual studio 2012 compiler (vc11).
I would like to read few lines (character by character) from input file (which is redirected as stdin). But after reading each line, I would like to fflush stdin.
Let me explain in details: I turn off stdin buffering by setvbuf function (without this stdin would be buffered and first flush clears the whole input). Then program reads few lines from input file. Characters are read one by one (fgetc function). After each line, I clear stdin with fflush. On Windows fflush on input stream is definied. According to MSDN: "If the stream is open for input, fflush clears the contents of the buffer. " https://msdn.microsoft.com/en-us/library/aa272686(v=vs.60).aspx
But I don't understand how it works. You can see that sometimes first character (of line) is not read from input. Probably due to fflush (maybe fflush clears this first character from stdin buffer?). But it happens only for few lines (some lines are read with first character).
Why does this first character disappear (sometimes)?
How can I correct this? (assuming that I would like to call fflush(stdin) after reading each line).
Program:
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int main()
{
setvbuf(stdin, 0, _IONBF, 0);
std::string text[6];
for(int i = 0; i < 6; i++)
{
int input;
char cc;
do
{
input = fgetc(stdin);
cc = (char)input;
if (cc != '\n' && input != EOF)
{
text[i] += cc;
}
}
while (cc != '\n' && input != EOF);
fflush (stdin);
}
for(int i = 0; i < 6; i++)
{
std::cout <<text[i] << std::endl;
}
return 0;
}
Input file:
first
second
third
fourth
fifth
sixth
Execution command:
.\main.exe < input
Output (please note missing first character in few lines):
first
econd
hird
fourth
fifth
ixth