help with solving a problem

hi all,
im new to c++ and im working with the "jumping to c++" book.
i need help with one of the problems- chapter 4 problem 1:
"1. Ask the user for two users' ages, and indicate who is older; behave differently if both are over
100"

this is what i came up with ( and ofcourse its not working):

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
26
27
#include <iostream>
#include <string>

using namespace std;

int main()
{
   string first_age;
   string second_age;

   cout << "enter first age: " << "\n";
   getline( cin, first_age, '\n' );
   cout << "enter second age: " << "\n";
   getline( cin, second_age, '\n' );
   if ( ( first_age+second_age ) > 100 )
   {
       cout << " above 100\n";
   }
   else if ( first_age > second_age )
   {
       cout << " first is older\n";
   }
   else
   {
       cout << "second is older\n";
   }
}


thanks in advance!!!!!!
Why are you not using integers for the ages?
1
2
3
int age1, age2; 
std::cout << "Enter 1st age:"; 
cin >> age1; 


Comparing strings like this:
1
2
3
4
std::string firstage, secondage; 
if(firstage > secondage) 
{
}


Is not going to work how you expect.

A comparison of integers will work like you expect:
1
2
3
4
int a = 41, c = 29; 
if(a > c)
{
}


Also, if both are over 100 means if age1 and age2 are over 100, not if the sum of the ages is over 100.
Last edited on
Just wondering why you use a string instead of a numerical type ? Are you aware of what the > and + operators do with strings?

Good Luck!!
"both are over 100" is not same as "sum of ages is over 100".

"Behave differently if ..." says to me that you should still tell the older, but in different tone than for the youngsters.

You read in strings. op+ for strings is a concatenation. op> for strings does lexicographical compare.

"foo" + "bar" == "foobar"
"foo" > "bar" == true
"7" > "10" == true
"42" > "7" == false

You have to convert the input into integers. Operator >> and a test that input did succeed.
Topic archived. No new replies allowed.