The strangest behavior with C++ iostream I've ever seen
Page 2 of 2

Author:  Ethin [ Thu May 12, 2022 4:07 pm ]
Post subject:  Re: The strangest behavior with C++ iostream I've ever seen

nullplan wrote:
Ethin wrote:
But the check to see if c != 0 or c == 0 below that negates that need.
Well no. According to cppreference:
https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2 wrote:
Behaves as an FormattedInputFunction. After constructing and checking the sentry object, which may skip leading whitespace, extracts a character and stores it to ch. If no character is available, sets failbit (in addition to eofbit that is set as required of a FormattedInputFunction).
If I read that right, the value of c is undefined on failure. In any case, it appears that operator>> is overkill anyway, since you only want to extract single characters from the stream. So one possible solution would be to ditch it and instead use get() and unget(). get() without arguments returns the next character or EOF, but alternatively you can pass a character variable as reference, and then the return value can be converted to bool to get the state, so in effect:
char c;
while (in.get(c))
That ought to do it.

Thanks for all the help :). We managed to solve the problem though. My professor just looked at the code that I'd pre-generated -- I've always included the generated listing but he usually has my code generate it himself, and so he just fell back to what my code had generated and graded it on that. I did point him to this topic though if he wants to tinker with my code to try to fix it though. I might pick this project back up in the future but I doubt it. I appreciate all the help and your suggestions were useful and I learned some things along the way. I do wish that C/C++'s eof stuff wasn't so finicky though -- its incredibly annoying to have all these different functions that return EOF at seemingly random points, with very little consistency between them (or so it seems). I mean, we might as well use platform-specific API calls if the C/C++ stdlib is going to be so weird. But maybe its the OS that does that... But that doesn't mean that the standard can't impose hard requirements on the behavior of these functions to make them match the behavior in other languages.

Page 2 of 2 All times are UTC - 6 hours
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group