Help with string/getline/ignore functions

Hey y'all!
I am extremely new to programming and am really struggling in my class. I've finally caught up with basic, simple programs, but now we're learning about strings and the ignore/getline functions, and I just don't understand. Please help with this question and explain why my program isn't working.
Thank you in advance!

Write a program that inputs the names of two people as well as their ages.
Use the ignore function between entering the names and the ages.
Create an if statement to determine which person is older.
Write a display statement that states the names and ages of each person and which person is older.
If they are both the same age,
display their names and ages and state that they are the same.
From this point on you are encouraged to use strings for names and descriptions. It will make your programs more realistic.

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
  #include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int main()
{
//declare variables
string name1 = "";
string name2 = "";
int name1Age = 0;
int name2Age = 0;

//get input
cout << "Enter first name: ";
getline(cin, name1);
cin.ignore(100, '\n');
cout << "How old are they?: ";
cin >> name1Age;
cin.ignore(100, '\n');
cout << "Enter second name: ";
getline(cin, name2);
cin.ignore(100, '\n');
cout << "How old are they?: ";
cin >> name2Age;
cin.ignore(100, '\n');

if (name1Age == name2Age)
{
cout << "Ages are the same" << endl;
}
if (name1Age > name2Age)
{
cout << name1 << "is older than" << name2 << endl;
}
if (name1Age < name2Age)
{
cout << name2 << "is older than" << name1 << end;
}

system("pause");
return 0;
}
> and I just don't understand
¿what you don't understand?

Suppose that your input is [output]hello world
54
the answer
42[/code]or condensed as "hello world\n54\nthe answer\n42\n"when you do `getline()' it would stop at the end of line ('\n') and it would discard it, the input would be then "54\nthe answer\n42\n"
but when you simply do `cin>>var', the end of line character remains in the buffer "\nthe answer\n42\n"
so now, a `getline()' would give you an empty string.


With that, you may understand why
Use the ignore function between entering the names and the ages.
is incorrect

1
2
3
4
5
6
7
8
9
10
11
//get input
cout << "Enter first name: ";
getline(cin, name1);
cout << "How old are they?: ";
cin >> name1Age;
cin.ignore();
cout << "Enter second name: ";
getline(cin, name2);
cout << "How old are they?: ";
cin >> name2Age;
cin.ignore();



Also, you've got a typo on line 38
Topic archived. No new replies allowed.