与cin一起使用的getline()函数

时间:2017-03-25 18:47:32

标签: c++ inputstream cin getline

int main(){ 
    string name, StudentNumber, Marks;
    cout << "Enter name:\n";
    cin >> name;
    cout << "Enter space separated class marks:\n";
    getline(cin, Marks);
    cout << "\n";
    cout << Marks;
}

当我运行上面的代码时,跳过getline(cin, Marks)语句并且程序终止,即用户无法输入类标记。我尝试稍微修改代码:

int main(){ 
    string name, Marks;
    cout << "Enter name:\n";
    cin >> name;
    cout << "Enter space separated class marks:\n";
    cin >> Marks;
    getline(cin, Marks);
    cout << "\n";
    cout << Marks;
}

这是我得到的输出:

Enter name:
John
Enter space separated class marks:
78 76 54 79

 76 54 79

第一个标记(78)尚未添加到变量Marks。有人可以帮助解释为什么会这样吗?我是C ++的新手。

1 个答案:

答案 0 :(得分:-2)

像这样写

    int main(){ 
        string name, Marks;
        cout << "Enter name:\n";
        cin >> name;
        cout << "Enter space separated class marks:\n";
getline(cin, Marks);
    cout << "\n";
    cout << Marks;