Conversion Help

Enter as many numbers as you want as long as the user doesn't type 'e' to exit.

Problem: When I enter a number, it works fine, but if I enter e then it'll go in an infinite loop since the letter is being stored in an int variable. How can I (when I press 'e') make it convert to a char to make it end the program?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main()
{
  int num;
  cout << "Enter a number or press e to exit:";
  cin >> num; //here's the problem
  while(num != 'e')
  {
   cout << "Number entered was " << num << endl;
   cout << "Enter a number or press e to exit:";
   cin >> num;
  }
  return 0;
}


Our class has just started c++ and we have not learned arrays and classes yet, so I'm guessing there is a way to do this without it? Or no?
The problem is that the std::cin input stream goes into an error state when the user enters a character instead of a number. It goes into an error state because it's "smart" enough to recognize that e isn't a number.

In the end, the problem is that you ask your user to input either a character or a number, but std::cin only ever expects a number.

The "professional" approach would be to input a string, then search for patterns in it, preferably using the regex library of C++11.
http://www.cplusplus.com/reference/regex/

The simpler approach would be to just make the program stop when anything other than a number is entered. You achieve this by checking the state of the input stream:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main()
{
  int num;
  cout << "Enter a number or ANYTHING OTHER to exit:";
  cin >> num;
  while(cin.good())
  {
   cout << "Number entered was " << num << endl;
   cout << "Enter a number or ANYTHING OTHER to exit:";
   cin >> num;
  }
  return 0;
}


The above could be written more elegantly if you take advantage than an input stream can be converted to a boolean depending on its state. Meaning std::cin becomes false if it entered an error state, otherwise becomes true.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
  int num;
  cout << "Enter a number or ANYTHING OTHER to exit:";

  while(cin >> num)
  {
   cout << "Number entered was " << num << endl;
   cout << "Enter a number or ANYTHING OTHER to exit:";
  }
  return 0;
}


Note that we no longer care if the user entered the character e (although I believe the emphasis was obvious enough). If the user enters anything other than a number, the program quits.

See also:
http://www.parashift.com/c++-faq/stream-input-failure.html
Thank you! cin.good() did the trick!
Topic archived. No new replies allowed.