tags:

views:

107

answers:

3

Something like this

cout << "Enter the number of columns: " ;
    cin >> input ; 
    while( input != int ){
      cout << endl <<"Column size must be an integer"<< endl << endl;
      cout << "Enter the number of columns: " ;
      cin >> input ;
   }
+1  A: 

You can't do it like that; input has to have some concrete type.

The simplest approach that will work is to read a string from cin, then convert it to an integer in a second step with strtol or one of its relatives, and issue an error message if strtol doesn't consume the whole string.

Zack
+2  A: 

cin will do this for you, kind of. cin will fail if it receives something that is not of the same type as input. What you can do is this:

int input;
while(!(cin >> input))
{
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cout << endl <<"Column size must be an integer"<< endl << endl;
    cout << "Enter the number of columns: " ;
}

The cin.clear() clears the error bits, and cin.ignore() clears the input stream. I'm using number_limits to get the maximum size of the stream, that requires that you #include<limits>. Alternatively you can just use a big number or a loop.

Niki Yoshiuchi
Thanks, is there any way to make it so floating point #'s generate the same response?
Anteater7171
This answer is correct, but one thing that should be added: You'll need to declare variable "input" as an integer type before this, like `int input;`
aschepler
To cut all this boilerplate code, you could use this function: http://stackoverflow.com/questions/2256527/how-to-clear-the-unneccessary-input-stream-in-c/2257168#2257168
Matteo Italia
@Anteater - this code will work for any type. `cin` expects to receive input that is the same type as the variable passed to it (`input` in this case). I have edited my code so that `input` is declared as an `int`, but you can just as easily declare it as a `float`.
Niki Yoshiuchi
+2  A: 
 #include<iostream.h>
 using namespace std;
 int main()
 { 
int x;
int input;
  while(!0){
       cout<<"Enter your option :";
       cout<<"1 .Enter Column size :"<<endl;
        cout<<"2.Exit "<<endl;
      cin>>x;
     switch(x)
         {
            case 1:   cout << "Enter the number of columns: "<<endl ;
                      cin>>input;
                     if(input>0)
                       cout << "The number of columns: is "<<input<<endl ;
                     else 
                       cout << "Enter the number of columns as integer  "<<endl ;

             case 2:exit(0);            
        }
   };
 return 0;
}
BE Student