1

After my first entry, my second entery name field fills up with the input buffer from the previous entry. Why? I am even using the getline but the problem still persists. Please help me with the problem. This is question from Jumping Into C++ book .

#include <iostream>
#include <string>

using namespace std;

struct Person
{
    string name;
    string address;
    long long int PhoneNumber;
};

void displayEntries(Person p[])
{
    int enteryNumber;
    cout << "Enter the entry number of the person for details(enter 0 to display all entries): ";
    cin >> enteryNumber;
    if(enteryNumber == 0)
    {
        for(int i = 0; i < 10; i++)
        {
            cout << "Entery Number: " << i + 1;
            cout << "Name: " << p[i].name << endl;
            cout << "Address: " << p[i].address << endl;
            cout << "Phone Number: " << p[i].PhoneNumber << endl;
        }
    }
    do
    {
        cout << "Entery Number: " << enteryNumber;
        cout << "Name: " << p[enteryNumber].name << endl;
        cout << "Address: " << p[enteryNumber].address << endl;
        cout << "Phone Number: " << p[enteryNumber].PhoneNumber << endl;
    } while (enteryNumber != 0);
}

int main()
{
    Person p[10];
    for(int i = 0; i < 10; i++)
    {
        cout << "Enter the details of the person\n\n";
        cout << "Name: ";
        getline(cin, p[i].name);
        cout << "Address: ";
        getline(cin, p[i].address);
        cout << "Phone Number: ";
        cin >> p[i].PhoneNumber;
        cout << endl;
    }
    displayEntries(p);
    return 0;
}
KaiserKatze
  • 1,521
  • 2
  • 20
  • 30
Dipesh BC
  • 37
  • 5

2 Answers2

1

cin >> p[i].PhoneNumber; only gets the number. That leaves the line ending still in the input buffer to be read the next time you try to read a line.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
1

You can see what is happening when you read the reference for getline:

When used immediately after whitespace-delimited input, e.g. after

int n; 
std::cin >> n; 
getline(cin, n); //if used here

getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

before switching to line-oriented input.

P.W
  • 26,289
  • 6
  • 39
  • 76