totallydialectical
totallydialectical

Reputation: 39

Variable isn't reading in correctly when i use getline( )

I am trying to write a simple address book practice program for a c++ text book i have. For some reason when i try to store text to string with getline(cin, variablename, '\n') it doesn't store anything.

I am compiling with the g++ compiler on Linux mint 17.1 Any help is greatly appreciated .

Here is my code so far:

#include <iostream>
#include <string>

using namespace std;

struct peopleData
{
    string name;
    string address;
    string phoneNumber;
};

using namespace std;


peopleData getData (string name, string address, string phoneNumber)
{
    peopleData person;
    person.name = name;
    person.address = address;
    person.phoneNumber = phoneNumber;
    return person;
}


int main ()
{
    int amount_of_people;
    string name;
    string address;
    string phoneNumber;

    cout << "How many people are you entering information for? ";
    cin >> amount_of_people;

    peopleData people[amount_of_people];

    for ( int i = 0; i < amount_of_people; i++)
    {
        cout << "What is person " << i + 1 << "'s name?\n";
        getline( cin, name, '\n' );
        cin.ignore();
        cout << "What is " << name << "'s address?\n";
        getline( cin, address, '\n' );
        cin.ignore();
        cout << "What is ";
        cout << name << "'s phone number?\n";
        getline( cin, phoneNumber, '\n' );
        cin.ignore();
        people[i] = getData(name, address, phoneNumber); 
    }

    cout << "Your address book is finished.\n";
    for ( int x = 0; x < amount_of_people; x++)
    {
        cout << people[x].name 
             << "'s address is "  << people[x].address 
             << "\nand their phone number is " << people[x].phoneNumber << endl;
    }

}

Upvotes: 2

Views: 96

Answers (2)

R Sahu
R Sahu

Reputation: 206607

  1. You need to ignore the rest of line after

    cin >> amount_of_people;
    

    Add the following right after the above line:

    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    
  2. Remove the calls to cin.ignore(); after the calls to getline(). getline() consumes the '\n' from the stream but does not add it to the output string.

Upvotes: 0

Rahul Manne
Rahul Manne

Reputation: 1249

Ok, so update: you should be calling cin.ignore() BEFORE getline and not after getline. If you want to do it your current way, you forgot to call cin.ignore() after you read the number, causing the first one to appear completely empty.

The previous answer was wrong, but the following statement still holds true:

Your '\n' is redundant. See http://www.cplusplus.com/reference/string/string/getline/ for reference.

Upvotes: 1

Related Questions