Just started learning C++ using Allain's "Jumping into C++". And I'm currently stuck on Chapter 4 Practice problem 1. I've actually done the thing and what is needed of me there, but I was just wondering about 1 thing. In the below code, then I build and run it, if I enter letters at the "person's age" prompt, the program just runs the rest of the code printing every 'cout' on the way. Is there any way to stop this behaviour?
#include <iostream>
#include <string>
int main()
{
std::string name1 = "<unknown>";
std::string name2 = "<unknown>";
int age1;
int age2;
// entering data
std::cout << "What's the name of the first person?" << "\n";
std::getline(std::cin, name1, '\n');
std::cout << "What's the name of the second person?" << "\n";
std::getline(std::cin, name2, '\n');
std::cout << "Please enter " << name1 << "'s age:" << "\n";
std::cin >> age1;
std::cout << "Please enter " << name2 << "'s age:" << "\n";
std::cin >> age2;
// checking if age != 0
if (age1 == 0 ) {
std::cout << "Age nas to be numeric and greater than 0. Please re-enter " << name1 << "'s age:"<< "\n";
std::cin >> age1;
}
if (age2 == 0) {
std::cout << "Age nas to be numeric and greater than 0. Please re-enter " << name2 << "'s age:"<< "\n";
std::cin >> age2;
}
// main task body
//checking if both are above 100
if (age1 > 100 && age2 > 100) {
std::cout << "Have they gone senile yet?";
}
//checking if person 1 is older than 100
elseif (age1 > 100) {
std::cout << name1 << " is one old fk!";
}
//same for person 2
elseif (age2 > 100) {
std::cout << name2 << " is one old fk!";
}
// are they the same age?
elseif (age1 == age2) {
std::cout << name1 << " and " << name2 << " are of the same age" << "\n";
}
// is there only a year difference?
elseif (age1 - age2 == 1) {
std::cout << name1 << " is older by a year." << "\n";
}
elseif (age2 - age1 == 1) {
std::cout << name2 << " is older by a year." << "\n";
}
//main comparison
elseif (age1 > age2) {
std::cout << name1 << " is older by " << age1 - age2 << " years." << "\n";
}
elseif (age1 < age2) {
std::cout << name2 << " is older by " << age2 - age1 << " years." << "\n";
}
}
Stream std::cin can read data only when it is in a good state. If an error occured (you entered a letter instead of a number) the state of the stream is bad and it read nothing until you will clear the state.