0

why does when enter 'q' ( or any char)

double x;

x = cin.get();

cout << x << endl;

return the char value for the character entered, but

    double x;

    cin >> x;

    cout << x << endl;

returns a random value for 'q'

Bbvarghe
  • 267
  • 2
  • 5
  • 18

2 Answers2

4

Like you say, std::istream::get gets a character from the input stream. For example, if you enter the digit 1 as input, it returns the ASCII code for the character '1' which is 49 decimal (on systems that use ASCII, which is almost everything).

When you use the input operator >> that function reads and parses the input into the correct format. So if you use >> with a double variable, and enter 1 you will get the value 1.0 in the variable.

The problem you have is that when the input operator >> can't properly parse the input, like when you enter a letter instead of a digit, then the input operator will fail and not set the variable, meaning you print an uninitialized variable which is undefined behavior. Note that this behavior changed in C++11 (see e.g. this old answer of mine).

You have to remember that a stream object can be used as a condition, and that the input operator function returns the stream in question. So you can do e.g.

if (std::cin >> x)
    std::cout << x << '\n';
else
    std::cout << "Error in input\n";
Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

std::get() reads input as unformatted integral value, so it succeeds as it doesn't have to format what it reads into any specific type. But operator>> reads input as formatted data, so it has to format what it reads into the given type. Since in your case, the input 'q' is not suitable for double, the formatting fails.

Nawaz
  • 353,942
  • 115
  • 666
  • 851