getline(cin,string)不是最后一行代码

时间:2016-02-03 22:59:09

标签: c++

我有以下简单程序,但最后一行代码getline(cin, topicClass)永远不会被执行。但是,如果我使用正常执行的cin>>topicClass。你可以帮我解决这个问题吗?感谢

#include <iostream>
#include <string>
using namespace std;

void InfoInput()
{
    string classID;
    string teacherName;
    int totalStudent;
    string topicClass;
    cout<<"Enter class ID"<<endl;
    getline(cin, classID);
    cout<<"Enter teacher's name"<<endl;
    getline(cin, teacherName);
    cout<<"Enter total number of students"<<endl;
    cin>>totalStudent;
    cout<<"Enter topic of class"<<endl;
    getline(cin, topicClass);
    //cin>>topicClass;
}

int main ()
{

    InfoInput();
}

3 个答案:

答案 0 :(得分:2)

你的问题在上面,用这一行:

cin>>totalStudent;

这不读一行。输入输入并(我假设)按ENTER键。 \n保留在std::cin的缓冲区中,并在下一条指令中显示为空行:

getline(cin, topicClass);

要修复,请使用以下代码:

cin>>totalStudent;
while(std::isspace(cin.peek())
    cin.ignore();
cout<<"Enter topic of class"<<endl;
getline(cin, topicClass);

答案 1 :(得分:0)

在读取\n作为整数后,cin中仍有totalStudent,因此您需要首先从系统中获取\n,然后阅读下一个字符串

#include <iostream>
#include <string>
using namespace std;

void InfoInput()
{
    string classID;
    string teacherName;
    int totalStudent;
    string topicClass;
    cout<<"Enter class ID"<<endl;
    getline(cin, classID);
    cout<<"Enter teacher's name"<<endl;
    getline(cin, teacherName);
    cout<<"Enter total number of students"<<endl;
    cin>>totalStudent;
    cout<<"Enter topic of class"<<endl;
    getline(cin,topicClass);
    getline(cin, topicClass);
    //cin>>topicClass;
}

int main ()
{

   InfoInput();

}

答案 2 :(得分:0)

您的classIDteacherName是局部变量,并在执行后离开函数消失。你必须弄清楚某些方法,比如通过引用传递参数,以在函数之间共享变量。