0

In most of my code, the in.peek() works as getting whatever the next char is supposed to be. However, when it is reading some symbols, it returns a number rather than the char, and I am not sure how to fix it to get the symbol I want.

The text file reads:

print "Good morning!!";

but during the " char I use file.peek() to read the next symbol is a ; to change the state of my switch, but it comes out as a number instead of the symbol.

This is how I am trying to print, I even created a temp char and set it to in.peek(), but that just comes out as a blank space.

char temp = in.peek();
cout<<"hit  " << ch << " "<< in.peek()<<" "<<temp << endl;

The output is: "hit " 10 "

With the last bit being a blank space. Does anyone know how I can fix this so I get the ;?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Zea R
  • 19
  • 3
  • according to the docs I see, it returns an int. That int may typically be displayed as a char in some places, presumably ascii? – Kenny Ostrom Nov 04 '20 at 19:46
  • Same reason why getchar and friends return int [Difference between int and char in getchar/fgetc and putchar/fputc?](https://stackoverflow.com/q/35356322/10147399) – Aykhan Hagverdili Nov 04 '20 at 19:54

1 Answers1

0

peek returns an int (to account for possibility of eof()). To make sure cout recognizes it as a char, you can cast it (though this will produce incorrect values if you did hit EOF), e.g.:

cout << "hit  " << ch << " " << static_cast<char>(in.peek()) << " " << temp << endl;
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271