0

Possible Duplicate:
Why is iostream::eof inside a loop condition considered wrong?

I was reading a group of characters via cin.get() and I noticed that my cin.get() was getting an exra character at the end of the input. Might anyone know how to fix this? Here's my code:

unsigned char c;

while(!cin.eof())
{
   c = cin.get();
   cout << (int)c << endl;
}

My issue is that the character it gets is one of 255 ascii value. I simply don't want it to get this extra character, but if the user enters in a ascii value of 255 without it being a garbage character at the end, then that should be fine. An example would be so for my output:

if I entered in abc\n in my output:

I get 97 98 99 10 255

but I want: 97 98 99 10

Any ideas on how to fix this? Thanks!

Community
  • 1
  • 1
user200081
  • 553
  • 2
  • 10
  • 24

2 Answers2

3

Never use cin.eof() as a loop condition. It almost always produces buggy code, as it has here.

Instead, try:

int c;
while ( (c=cin.get()) != EOF ) {
  cout << c << endl;
}

Or:

char c;
while (cin.get(c)) {
  cout << (int)c << endl;
}
Community
  • 1
  • 1
Robᵩ
  • 143,876
  • 16
  • 205
  • 276
  • Although you should probably not use `EOF` since the trait may return another value on end of file than `-1`, right? – Alexis Wilke Jun 09 '19 at 05:37
  • 1
    @AlexisWilke - Perhaps generally, but not specifically for `cin`. `std::cin` will always use `std::char_traits`, which uses `EOF`. – Robᵩ Jun 18 '19 at 03:58
3

The get() function with no arguments returns an int_type, not a char. At the end of the stream, it returns a special non-character value that indicates end of file (usually -1). By assigning the result of cin.get() directly to an unsigned char, you are inadvertently throwing away this eof information. The relevant documentation quote is:

1) reads one character and returns it if available. Otherwise, returns Traits::eof() and sets failbit and eofbit.

Greg Hewgill
  • 828,234
  • 170
  • 1,097
  • 1,237