I'm trying to make a simple program that asks 2 users for their name and age and then does a simple calculation to see who is older and then says "user x is older than user y by z years." I've been having trouble with the cin function. Before, I would execute the program and it would ask the user for their name and then skip over everything else. I figured out how to get it to wait for user input but it just seems really clunky to me. I was recommended to use cin.clear and cin.sync every time I asked for a users age. I'm using getline for their names.
Is there a better way to do this? I've tried searching for the solution but I'm not getting a straight answer. Thanks.
#include <iostream>
usingnamespace std;
int main()
{
//Asking users for name and age
int age1;
int age2;
string name1;
string name2;
cout << "Please enter your name.\n";
getline(cin,name1,'\n');
cout << "Please enter your numerical age.\n";
cin >> age1;
cin.clear();
cin.sync();
cout << "Second user, please enter your name.\n";
getline(cin,name2,'\n');
cout << "Please enter your age.\n";
cin >> age2;
cin.clear();
cin.sync();
//Declaring the int dif1 and dif2
int dif1;
int dif2;
dif1 = age1 - age2;
dif2 = age2 - age1;
//printing text based on age difference between two people
if ( dif1 > 0 )
{
cout << name1 << " is older than " << name2 << " by " << dif1;
if ( dif1 == 1 )
{
cout << " year." << endl;
}
else
{
cout << " years." << endl;
}
}
elseif ( dif2 > 0 )
{
cout << name2 << " is older than " << name1 << " by " << dif2;
if ( dif2 == 1 )
{
cout << " year." << endl;
}
else
{
cout << " years." << endl;
}
}
else
{
cout << "You two are the same age. Good job.\n";
}
return 0;
}
You may want to see about increasing your compiler warning level, your compiler should be able to warn you about a couple of issues.
main.cpp||In function ‘int main()’:|
main.cpp|38|warning: suggest parentheses around assignment used as truth value [-Wparentheses]|
main.cpp|50|warning: suggest parentheses around assignment used as truth value [-Wparentheses]|
||=== Build finished: 0 errors, 2 warnings (0 minutes, 1 seconds) ===|
I thought I needed to use the == since it's comparing the value, not assigning a value. I deleted the spaces I put inside the argument and now it's not giving me any warnings. Not sure if that's what the problem was but it appears to have fixed it.
Edit: Nevermind. I had edited my OP a few seconds after I posted to change to the == operator after I realized the mistake. That caused confusion. Sorry.