使用getline()时,变量无法正确读取

时间:2015-01-02 23:18:28

标签: c++

我正在尝试为我所拥有的c ++教科书编写一个简单的地址簿练习程序。出于某种原因,当我尝试使用getline(cin,variablename,'\ n')将文本存储到字符串时,它不存储任何内容。

我正在使用Linux mint 17.1上的g ++编译器进行编译 非常感谢任何帮助。

到目前为止,这是我的代码:

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

}

2 个答案:

答案 0 :(得分:1)

好的,所以更新:你应该在getline之前调用cin.ignore(),而不是在getline之后调用。如果你想以当前的方式做到这一点,你忘记在读取数字后调用cin.ignore(),导致第一个看起来完全为空。

之前的回答是错误的,但以下陈述仍然适用:

你的'\ n'是多余的。请参阅http://www.cplusplus.com/reference/string/string/getline/以供参考。

答案 1 :(得分:0)

  1. 您需要忽略

    之后的其余部分
    cin >> amount_of_people;
    

    在上一行之后添加以下内容:

    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    
  2. 在拨打cin.ignore();后,取消对getline()的来电。 getline()使用流中的'\n',但不会将其添加到输出字符串中。

相关问题