vendredi 2 janvier 2015

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;
}

}

Aucun commentaire:

Enregistrer un commentaire