getline(cin.name) gets skipped

getline(cin.name) gets skipped

本文关键字:gets skipped name cin getline      更新时间:2023-10-16

我从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()。