cin.getline()不会根据空格分开输入?

时间:2016-06-17 10:03:36

标签: c++ string getline

我一直在寻找我的问题的答案,但找不到答案。 我正在使用:

cout << "Enter student's first name and last name:\n";
cin.ignore(100, '\n');
cin.getline(name, 20, ' ');
cin.getline(family, 20, ' ');

但是输入[例如:David Jones]没有分开,只在'name'中。

为什么getline()不用它的分隔符分隔输入? 谢谢!

全功能:

    //add a Student to Students.txt
void addStudent(fstream &f1)
{
    //exception
    if (!f1)
        return;
    int id;
    char family[20];
    char name[20];
    bool courses[5];
    cout << "Enter student's ID:\n";
    id = getInteger(id, 1, 100); // id range: (1 <= id <= 100)
    cout << "Enter student's first name and last name:\n";
    cin.ignore(100, '\n');
    cin.getline(name, 20, ' ');
    cin.getline(family, 20, ' ');
    cout << "Enter 0/1 for each of the student's 5 courses\n";
    int boolean; // 0/1 input
    for (int i = 0; i < 5; i++)
        courses[i] = getInteger(boolean, 0, 1);
    //find out if this id is already taken [=> return]
    if (!f1)
        throw "Error opening -Students.txt- from Project directory.\n";
    if (isInFile("Students.txt", id))
        return;
    /*continue in case the opening was successful AND the id doesn't already exist*/
    Student s(id, family, name, courses);
    //write to our file
    f1.seekp((id - 1) * sizeof(Student)); //(id-1): ids start from 1
    f1.write((char*)&s, sizeof(Student));
}

1 个答案:

答案 0 :(得分:0)

我不明白为什么你打cin.ignore(100, '\n');我觉得这让你感到困惑。

解决方案可能是,避免ignore(),只需写

即可
cin >> name >> family;

但是如果你想使用getline(),我建议

cin.getline(name, 20, ' ');
cin.getline(family, 20, '\n'); 

否则你必须在姓氏后添加一个空格。