C++ getline(cin,字符串)未在代码的最后一行执行
我有下面的简单程序,但是最后一行代码C++ getline(cin,字符串)未在代码的最后一行执行,c++,C++,我有下面的简单程序,但是最后一行代码getline(cin,topicClass)永远不会执行。但是,如果我使用正常的cin>>topicClass执行。你能帮我解决这个问题吗?谢谢 #include <iostream> #include <string> using namespace std; void InfoInput() { string classID; string teacherName; int totalStudent;
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();
}
#包括
#包括
使用名称空间std;
void InfoInput()
{
字符串classID;
字符串教师名称;
国际学生;
字符串主题类;
在将totalStudent
读取为整数后,\n
仍保留在cin
中,因此您需要首先从系统中获取该\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();
}
#包括
#包括
使用名称空间std;
void InfoInput()
{
字符串classID;
字符串教师名称;
国际学生;
字符串主题类;
cout您的问题在上面,用这行代码:
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);
cin>>totalStudent;
while(std::isspace(cin.peek())
cin.ignore();
cout你的classID
和teacherName
是局部变量,在执行离开函数后消失。你必须想办法,比如通过引用传递参数,在函数之间共享变量。可能的重复,没有。这是一个“钉子!”@AlgirdasPreidžiusHow您是否确定从未执行过getline
?脱离主题:ifcin>>totalStudent;
未提供整数(即使是一个非常不可能的整数,也无法放入int
)cin
将处于未清除的错误状态,可能会导致程序死机。每次读取后,您需要检查cin
或任何其他流的状态,以确保数据已读取,如果未读取,则清理混乱。非常感谢您的回答,我已获得它。