Getline

After the for loop for input has run the first loop (successfully), It ask's
for Name, But alway's skip's the input: getline(std::cin, Person[i].Name);
I've tried using std::cout << std::endl; to flush any previous input, And
have now run out of idea's how to fix this.
If i swap the lines for Name and DOB, DOB input now get's skipped.

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

class People
{
public:
    std::string Name;
    std::string DOB;
    int Age = 0;
};

int main()
{
    std::string PerName;
    People Person[3];
    for (int i = 0; i <= 2; ++i)
    {
        std::cout << "\nEnter person " << i + 1 << "'s name: ";
        getline(std::cin, Person[i].Name);
        std::cout << "\nEnter person " << i + 1 << "'s date of birth: ";
        getline(std::cin, Person[i].DOB);
        std::cout << "\nEnter person " << i + 1 << "'s age: ";
        std::cin >> Person[i].Age;
    }
    std::cout << "\n\ndatabase:";
    for (int i = 0; i <= 2; ++i)
    {
        std::cout << '\n' << Person[i].Name << " " << Person[i].DOB << " " << Person[i].Age;
    }
    return 0;
}
Just need a std::cin.ignore(); after line 23.
Thank's Yanson :)

Can anyone explain what was happening before std::cin.ignore() was used?
When you used a regular std::cin >>, it only got what it wanted and it left the newline there. std::getline on the next loop saw that and thought the user pressed enter without typing anything. Remember: >> just gets what it wants and leaves, whereas std::getline cleans up after itself.
Last edited on
Thank's L B.
Topic archived. No new replies allowed.