i have a question which is if i am using an integer but then i wrongly enter a character, how can i make the input?

#include <iostream>
using namespace std;
int main ()
{
int num;
cout<<"Enter a number:";
cin>>num;
return 0;
}
when i enter "a" it will be popping out of the screen. how do i solve it by repeating the "Enter a number" to continue requesting people to enter the data???
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>
using namespace std;
int main ()
{
    string num;
    do
    {
        cout<<"Enter a number:";
        cin>>num;
        if(num[0]<48 || num[0]>57)
            cout<<"Not a number "<<endl;
        else
        {
            cout<<"You entered "<<num<<endl;
            break;
        }
    }
    while(true);
    return 0;
}
closed account (jwkNwA7f)
You can use cin.fail().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int main ()
{
    int num;
    cout<<"Enter a number:";
    cin>>num;
    if (cin.fail())
    {
           cin.clear();
           main();
    }
    return 0;
}


Also, can you use code tags next time.
Hope this helped!
@ cppprogrammer297:

Calling main is forbidden by the standard, and if cin.fail returns true, you don't remove the offending input from the stream so you end up with an endless recursive cycle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <limits>

int getnum(const char* prompt)
{
    int num ;

    while ( std::cout << prompt  &&  !(std::cin >> num) )
    {
        std::cout << "Invalid input.\n" ;
        std::cin.clear() ;
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return num ;
}

int main()
{
    int n = getnum("Enter a number: ") ;
    std::cout << "You entered " << n << '\n' ;
}
cppprogrammer297
did you run your code? lol
closed account (jwkNwA7f)
Oh, sorry, I had to go do something, so I was in a hurry.
I did not get to run my code. Also, I thought you could call main() like that.
only chriscpp can run... others one cannot run... btw thank you... problem solved
Topic archived. No new replies allowed.