"invalid conversion from string to an integer"

Here is my delima:

1
2
3
4
while(((menu_choice > f_lines) && (menu_choice < 1)) || (menu_choice == 0))
{
    cin>> menu_choice;
}


This piece of code I wrote for a program gets a number between the values specified (no greater than the number of options there are, and no less than 0). I used cin>> because getline() is not needed in this scenario, we want numbers not a string. But, what happens when we enter a string anyway? I'll tell you: The dam thing doesn't know what to do with it. So my question is:

Since we can't add a string argument to pervent the entering of a string (integers can't be strings) into the command line, what can we do to squeez this bug out of my program?
Try something like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
  string s;
  int    menu_choice(0),f_lines(10);
  cout << "Enter selection: ";
  getline(cin,s);
  stringstream iStr(s);
  while( !(iStr >> menu_choice) ||  
           menu_choice > f_lines || menu_choice < 1 ) {
     iStr.clear();
     cout << "Error! Re-enter selection: ";
     getline(cin,s);
     iStr.str(s);
  }
  cout << "Menu Choice: " << menu_choice << endl;
  return 0;
}
./a.out
Enter selection: 400
Error! Re-enter selection: dog
Error! Re-enter selection: 4
Menu Choice: 4
Last edited on
Topic archived. No new replies allowed.