使用getline而不是cin获取结构时的错误

bug when use getline insead of cin for struct

本文关键字:结构 错误 获取 cin getline 使用      更新时间:2023-10-16

我的代码做得很好,但是当我将cin>>new_person.address更改为getline时,当我运行它时,我有bug。

#include <iostream>
using namespace std;
struct person
{
    string name;
    string address;
    int phone_number;
};
person getNewPerson()
{
    person new_person;
    cout<<"Enter a name ";
    cin>>new_person.name;
    cout<<"Enter an address ";
    getline(cin, new_person.address, 'n');
    cout<<"Enter a phone number ";
    cin>>new_person.phone_number;
    return new_person;
}
person printPerson(person a_person)
{
    cout<<"This person name is: "<<a_person.name<<endl;
    cout<<"His address is: "<<a_person.address<<endl;
    cout<<"His phone number is: "<<a_person.phone_number<<endl;
}
int main()
{
    person my_person=getNewPerson();
    printPerson(my_person);
}

当我使用getline(cin, new_person.address, 'n');时,它会无缘无故跳过该语句并转到下一个语句。不知道发生了什么,请复制并粘贴代码,你会明白的。

就是这样设计的。在c++中,std::cin >> str;读取流中的下一个单词。更具体地说,它读取下一个令牌,令牌由空格分隔,因此它们有效地表示一个单词。

使用getline功能输入多个单词