getline(cin.name) gets skipped
getline(cin.name) gets skipped
我从c++中的函数调用函数,该函数具有getline(cin,name)
行,其中name是字符串。第一次通过循环时,程序不等待输入。它会在其他所有循环中传递。知道为什么吗?
void getName (string& name)
{
int nameLen;
do{
cout << "Enter the last Name of the resident." << endl << endl
<< "There should not be any spaces and no more than 15"
<< " characters in the name." << endl;
getline(cin,name);
cout << endl;
nameLen = name.length();// set len to number of characters input
cout << "last" << name << endl;
}
while (nameLen < LastNameLength);
return;
}
确保上次从cin读取内容后没有剩余内容,例如:
在程序的前面一点:
int number;
cin >> number;
输入:
5
程序后面:
getline(cin,name);
和getline
似乎没有被调用,而是从上次输入时收集换行符,因为当您使用cin >>
时,它会留下新行。
可能是输入流的原因。getline函数在接收到第一个换行字符后停止读取输入。例如,如果在std::cin的缓冲区中有多个换行符,getline将在每次遇到换行符时返回。
检查您期望的输入
你有: cin & lt; & lt;variableName;
代码行数?当我使用:
时,我遇到了getline()跳过运行时错误cin & lt; & lt;intvariable和依次getline(cin, variable)。
这是因为cin流对象保存了一个输入缓冲区。当您输入换行符时,我假设它是从流向变量赋值的流中截断的,但仍然包含在cin对象实例本身中。
我使用的一个解决方法是cin.ignore();在 <<strong>>cin <<整数语句。另一个用户提到将来自getline的所有输入解析为整数、浮点数(不是根啤酒)和字符串。祝你好运,并检查你的代码的双重用途的cin & &;getline()。
相关文章:
- Turbo C++ cin() 不能与 gets() 一起使用
- 一起使用 GETS 和 CIN
- 在C/C++中检查数字是否为整数(不带scanf/gets/etc)
- gets() 二维数组
- gets() 不允许先执行 cout
- 如何解决"identifier 'gets'/'clrscr' is undefined"问题?
- gets()未在作用域中声明
- QJsonValue gets empty
- CPP中如何使用get gets()
- gets() 和 getch() 有什么区别?
- gets() 在第一次循环迭代中不起作用,但在后续迭代中工作
- 为什么gets()需要更多的字符
- gets() 不接受输入
- 函数中的 gets() 在第二次使用后被跳过
- Gets()导致内存损坏
- 为什么第一个gets()在这段代码中不起作用?
- dev 为什么在 dev c++ 中使用 "cin function" 后我无法使用"gets function"?
- 它的gets()被认为是C函数或c++函数
- getline(cin.name) gets skipped
- gets()中的错误,不是编译错误,而是无法接收输入