c++ problem

1
2
3
4
5
6
7


int num;

cout << "Enter a number: ";
cin >> num;


If user inserts a char, i want the program to print: "Please enter a number."

How can i do that?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main(){
    string in;
    int out;

    do {
        cout << "Enter a Number :";
        cin >> in;

        if( istringstream(in) >> out ){
            break;
        } else {
            cout << "Please enter a number" << endl;
        }
    } while( true );

    cout << "Your number is " << out << endl;

    return 0;
}


Maybe smt like this ???
You can also do it without the string or stringstream libraries.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main( int argc, char* argv[] )
{
   int x;

   std::cout << "Please enter an integer: ";

   while( !( std::cin >> x ) )
   {
      std::cout << "Invalid number, enter again:";
      std::cin.clear();
      std::cin.ignore( 256, '\n' );
   }

   std::cout << "Valid number entered\n";

   return 0;
}
Last edited on
Topic archived. No new replies allowed.