Hi all, I am new to C++ and I wrote a test program to print out characters that are left in the input-stream when cin encountered inappropriate input, however I encountered some strange phenomena when I tried to concatenate cout with cin.get(). I am not sure if this is a conventional way to do this but here's the essential part of my code that has this issue:
The problem is when I run the executable and input:
abc<Enter>
the actual content get printed out is:
cba
It seems that the order of the characters that are passed to the output-stream is reversed...
Another problem is I read somewhere that calling cin to build a new input-stream will cause the current output-stream to be flushed. However for the above code if I input:
a<Enter>
The program will continue to wait for additional input without printing out the character 'a' and '\n' that I have already inputed...
Any help on this will be appreciated...Thanks!
cin.get() returns the int-type-casted character that it gets from the input stream, the one that returns a reference to an stream object is an overloaded version of get(char&) as in cin.get(char&)...so there should not be any problems with this...the code can pass through compilation without errors or warnings
You are playing with side-effects. There is no guarantee that the cin.get() on the left will be called before the cin.get() on the right, or any other order.
This tells us that the get() function returns an int value (which we have casted to a char) and extracts a character. The question now is: which character? It appears that it is extracting the last character in the stream and returns its value. You were expecting it to extract the first (oldest) character in the sequence. I don't see this as being defined on cplusplus.com, but I am sure it is defined somewhere.
Thanks guys, I think this is a sequence point issue. The right-most cin.get() get called first and extracts the first character in the input-stream while the left-most cin.get() get called last and extracts the last character in the input-stream. However cout still prints from left to right which means it prints the return value of the first cin.get() that end up getting the last character in the input-stream. Thanks again for all the helpful comments.
> It is undefined because you are modifying cin multiple times (using get) in between sequence points.
> Thanks guys, I think this is a sequence point issue.
C++ does not have the concept of sequence points.
The three calls to std::cin.get() are indeterminately sequenced - ie. they may be sequenced in any order, but the three evaluations cannot overlap of interleave.
If C++ was illegal then C would be illegal too. Since C is a subset of C++ making one illegal would mean the other one would have to be illegal too as you couldn't have C++ without C. ;) I meant I didn't know you could have cin.get() in the same line as cout.