提示不会在getline处停止将名称存储到变量中

时间:2015-03-30 13:16:17

标签: c++

这是一个请求和打印一些信息的小程序。问题点是存储可能包含空格的名称。我的问题是,当达到Enter your name时,它会快速移至Enter your total marks,而不会让用户输入名称。为什么会这样?

#include <iostream>

using namespace std;

class StudentInformation {
protected:
    int studentID;
    string studentName;
    int totalMarks;
public:
    void input() {
        cout << "Enter your student id number: ";
        cin >> studentID;

        cout << "Enter your name: ";
        getline(cin, studentName);

        cout << "Enter your total marks";
        cin >> totalMarks;
    }

    void show() {
        cout << "Student ID: " << studentID << endl;
        cout << "Student Name: " << studentName << endl;
        cout << "Total Marks: " << totalMarks << endl;
    }
};

int main()
{
    cout << "Hello World!" << endl;

    StudentInformation stdinfo;

    stdinfo.input();
    stdinfo.show();

    return 0;
}

enter image description here

2 个答案:

答案 0 :(得分:3)

cin >>getline混合使用会导致问题。

  • cin >> studentID将换行符保留在流中。
  • getline直接看到了这一点,所以不要等待新的输入。

我更喜欢使用getline从实际流中读取数据,然后使用stringstream进行格式化提取。

或者在getline之前使用ignore

std::cin >> ...; // leaves trailing whitespace and newline
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // eat next newline
std::getline(std::cin, ...);

答案 1 :(得分:0)

只需使用 cin.getline(studentName, size)

即可