Reputation: 219
The else statement in this code does not execute, instead, when a character is entered, it would get stuck in a continuous loop, repeating the lines 33 and 35.
I want to check if the user input is not an integer in the else statement and ask the user again to specify the age.
#include <iostream>
#include <windows.h>
using namespace std;
class User {
string name;
public:
string getName(){
return name;
}
void setName(string newName) {
name = newName;
}
};
int main()
{
/** Initialise Variables */
string name;
int age;
User u1;
bool running = true;
while(running) {
/** Welcome Message w/ User's Name */
cout << "What is your name?: " << endl;
cin >> name;
u1.setName(name);
cout << "Welcome, " << u1.getName() << "!" << endl;
returnToAge:
Sleep(1000);
cout << u1.getName() << ", to continue, you have to be over 18." << endl;
Sleep(1000);
cout << "Please enter your age: " << endl;
cin >> age;
if (age >= 18) {
cout << "You may continue..." << endl;
Sleep(1000);
//Enter rest of questionnaire here
}
else if(age < 18) {
cout << "You are underage! Please try again!" << endl;
Sleep(1500);
goto returnToAge;
}
else {
cout << "INVALID INPUT!" << endl;
goto returnToAge;
}
}
}
Upvotes: 1
Views: 92
Reputation: 32852
Use std::cin::fail to check wether the user input is an integer.
Secondly, avoid maximum practice using goto
s, as it produces Spaghetti code structure. You can replace the goto
using a while
loop as follows:
while (true)
{
// code
std::cin >> age;
if (!std::cin.fail() && age >= 18) // if cin not failed && the codition
{
/* do something */
break; // break the loop!
}
else if (!std::cin.fail() && age < 18) // if cin not failed && the codition
{
/* do something goto removeed */
}
else { std::cout << "INVALID INPUT!" << std::endl; /* goto removeed */ }
}
Upvotes: 1
Reputation: 249153
You need to check if the input operation succeeded. The easiest way is:
if (cin >> age) {
// now use age
} else {
// error
}
Another way which is equivalent:
cin >> age;
if (!cin) {
// error
}
Upvotes: 3
Reputation: 2637
The problem is that cin >> age
will read an integer into age
(as that's the only thing age
can store), and no matter what integer that is (it's 0 for non-numbers), it will be either bigger or smaller than 18, hence why your else case is never reached.
To detect invalid input, you need to read in a string and then check whether that string represents a valid integer.
Upvotes: 2