How does if/else statements work ?

Hello everyone. I'm new in C++ and just discovered this website a couple days ago.
English in not my native language so I hope you're not gonna be too harsh on me !

I would like to know how if/else statements work ?
More specificaly : How can I tell my program to authorize only one type of input ?

Explanation :

I'm doing a "mini-crappy-game" where the user needs to enter a number.
But i'm always afraid of the user's input.
Like, if the user type something he's not supposed to, when I usually write my code, I even tend to use "string" to ask for an int.. It's pretty hard to explain when I don't really know the subject mysel so I'll just show you some examples :


I'm trying to choose the level of difficulty.
The user have to type a number (1 to 5) to choose.
(PS : This is an example, if there's little error, don't mind them, I wrote it to explain my problem)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

    int level(0);
    bool levelChoosen = false;

    cout << "Welcome, please choose a difficulty level" << endl;
    cout << "(1) = Easy" << endl;
    cout << "(2) = Medium" << endl;
    cout << "(3) = Hard" << endl;
    cout << "(4) = Nightmare" << endl;
    cout << "(5) = INSANE" << endl;

do {
    cin >> level;
        if (level == 1)
        {
            cout << "You choose the first level of difficulty" << endl;
            levelChoosen = true;
        }
        else
        {
            cout << "Please try again" << endl;
        }
}while(!levelChoosen);


Now, with this kind of code, if the user's input is not a number or if the number is too "high", the console will just repeat infinitely the thing which is in the else statement.
Like, If the user's input is "aze", the result will be :

Please try again
Please try again
Please try again
Please try again
Please try again
Please try again
Please try again
Please try again
etc...

I would like to know if there's a possibilty using something to tell the code "If the user's input is not a number, then go in the else." I already tried some things like "isdigit" etc, but couldn't make the code work :(
Make use of input bits. fail bit .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main()
{
	int a;
	cout<<"Enter a character instead: ";
	cin>>a;
	
	if(cin.fail())
		cout<<"Wrong input"<<endl;
	else
		cout<<"good input"<<endl;
	cin.ignore();
	return 0;
}
Since level is a numeric variable you can't enter characters, the extraction operator knows this and will place the stream into an error state. Before you can resume using the stream you must clear() the error state and extract and discard all of the characters that are in the input buffer. This is one of the reasons you probably prefer to use std::strings to handle user input, other than EOF a string will accept any character without error.

You can check the stream state in your if statement to determine if the stream is in an error state.

if (!cin || level == 1)
Last edited on
Apparently, the fail bit is working ! I'm gonna try to had it to my if/else statements in my code today and i'll be back to tell you if it's really working or if something is still fcked up !

Thank you so much for your answers guys ! I really appreciate it !
Sorry for the double post, I tried it several times and I got the exact same problem.
The "solution" for my problem can't contain a "return 0" 'cause i'm actually trying to do some "mods".

Like :

- Restart.
- Check if the input is right, if it's not, type again.

I found that I could apparently use cin.ignore() and cin.clear(), but when it checks the results for every character typed in..

Example :

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
int main()
{
       bool value = false;
	int level;
	cout << "Entrez un level" << endl;

do {
	cin >> level;

	if (level == 1)
    {
        cout << "You choosed the level 1" << endl;
        value = true;
    }
    else if (cin.fail())
    {
        cout << "That's not a numeric" << endl;
    }
    else
    {
        cout << "Wrong choice, type again." << endl;
    }
    cin.clear();
    cin.ignore();
}while(!value);


In this code, I put an If/else statement in a do/while so that will ask again to the user to type something. The problem is, When I run the code and try to type "aze" it gives me :

That's not a numeric
That's not a numeric
That's not a numeric

(So if I understood correctly, I guess that it check for every character typed. I would like to know if it's possible to change this. I want it to be only one single "That's not a numeric"..)
Or do I have another solution to "restart" the loop if the answer is not correct ?

Like :
- Choose your level
- The level typed in doesn't exist, please type it again
- You choosed the level X (And then it enters the game in this level)

Sorry if that's not clear.. Doing my best !
The problem is that you appear to have typed multiple characters, the ignore() function with the default arguments only remove one character, you need to remove them all.

Something like:

1
2
3
4
5
6
    else if (cin.fail())
    {
        cout << "That's not a numeric" << endl;
        cin.clear(); // Clear the error;
        cin.ignore(1000, '\n'); // Discard up to 1000 characters, or the end of line is detected.
    }


Nice, It's apparently working, thank you !
Can you please tell me why the console only accept a certain number of characters btw.. ?
I added your

cin.ignore(1000,'\n');

but if I type a certain number of characters, it fails(Didn't changed my code, I don't want to spam too much code so, If you could just check my code in my last answer !)

Example : (The numbers are what the user inputs. aka, me here)

654 : "Wrong choice, type again." (It's the "ELSE" statement here)
654654 : "Wrong choice, type again." (It's the "ELSE" statement here)
654654654 : "Wrong choice, type again." (It's the "ELSE" statement here)
6546546546 : "That's not a numeric" (It's the ELSE IF statement here)

Why is my code doing this ? Apparently when I type more than 10 characters, it fails and does not recognize the input as a "valid numeric".

Now, that's not a problem with this part of my code, but at the start, I will ask the user's name, to do a score pannel. If the name of the user have more than 10 characters, it would be a problem if the console doesn't recognize it as a "good answer".

Sorry to bother you guys, (especially you jlb) but thanks for the help !
Last edited on

Why is my code doing this ? Apparently when I type more than 10 characters, it fails and does not recognize the input as a "valid numeric".


This probably isn't about the number of characters, but about the magnitude of the number. What is the maximum value your int can hold?

I don't know if there's a thing who can show me the maximum value my int can hold, so i'm just gonna do it manually with several output :

Example : (What I Typed : The input it gives me)

99999999 : "Wrong choice, type again." (It's the "ELSE" statement here) [9 typed 8times]
999999999 : "Wrong choice, type again." (It's the "ELSE" statement here) [9 typed 9times]
9999999999 : "That's not a numeric" (It's the ELSE IF statement here) [9 typed 10times]etc
etc,etc.

I found out that my max value is somewhere between 2.100.000.000 and 2.200.000.000 apparently ><
I did some research and found that I could use :

1
2
int imin = std::numeric_limits<int>::min(); // minimum value
int imax = std::numeric_limits<int>::max();


But i'm too retarded to make it work... Sorry x_x
How about a simple cout statement? Don't forget to #include <limits>.
Yeah.. I'm retarded haha, sorry !

So, there it is :

minimum value : -2147483648
maximum value : 2147483647

Is there something to change theses numbers ?
No, if you need numbers outside that range then you would need to use a different type, a long for example. But no matter what type you use there are limits on how big the number can be when using integral types.

Okay ! Well thanks for the help jlb !
Now I can work on some code look forward for new things !
A really big thanks ! Sorry to have taken your time for little things like this !
Hope the better for you man, cya ! I'll just change it as solved ! :)
Topic archived. No new replies allowed.