0
#include <iostream>
#include <string>
using namespace std;

int main()
{
  // Declare a variable to store an integer
  int InputNumber;

  cout << "Enter an integer: ";

  // store integer given user input
  cin >> InputNumber;

  // The same with text i.e. string data
  cout << "Enter your name: ";
  string InputName;
  cin >> InputName;

  cout << InputName << " entered " << InputNumber << endl;

  return 0;
}

The above program produces wrong output if I enter some string for InputNumber , whats happening there , I assume that the memory allocated to Inputnumbe is overwritten but is that the problem? A sample output is also given.

correct output
Enter an integer: 123
Enter your name: asdf
asdf entered 123

wrong output
    Enter an integer: qwert
    Enter your name:  entered 0
hmjd
  • 120,187
  • 20
  • 207
  • 252
K_TGTK
  • 765
  • 1
  • 8
  • 24
  • Maybe test that `int` extraction just for lols. `if (cin >> InputNumber) { ... } else { // error message }` or some such may shed some light on your failed conversion. – WhozCraig May 20 '13 at 08:16

2 Answers2

8

When you entered a string for the integer, but tried to read it into an integer variable, the input stream entered into an error state. The error state is sticky until cleared. You can test the error state by checking if the input operation succeeded, or checking the good() method, or checking the bits on the rdstate() method. The error state can be cleared by using the clear() method.

jxh
  • 69,070
  • 8
  • 110
  • 193
  • Whats the way to resolve this in plain C , when using scanf("%d") for integer? – K_TGTK May 20 '13 at 08:32
  • 1
    It is similar. `scanf()` will return whether or not it successfully parsed the input stream. You can also check for an error with `ferror()`. You can clear the error with `clearerr()`. – jxh May 20 '13 at 08:35
4

Shockingly, "inputting a string to a number" isn't possible, which lead the C++ library designers to the surprising conclusion that it might be necessary to attempt input and then determine whether it succeeded. This is done like this:

int x;
if (std::cin >> x)
    sing_and_dance();
else
    cry();

Google std::istream if you want to see how to use it properly.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252