相关疑难解决方法(0)

为什么std :: getline()在格式化提取后会跳过输入?

我有以下代码提示用户输入他们的名字和状态:

#include <iostream>
#include <string>

int main()
{
    std::string name;
    std::string state;

    if (std::cin >> name && std::getline(std::cin, state))
    {
        std::cout << "Your name is " << name << " and you live in " << state;
    }
}
Run Code Online (Sandbox Code Playgroud)

我发现该名称已被成功提取,但不是州.这是输入和结果输出:

Input:

"John"
"New Hampshire"

Output:

"Your name is John and you live in "
Run Code Online (Sandbox Code Playgroud)

为什么输出中省略了状态名称?我给出了正确的输入,但代码忽略了它.为什么会这样?

c++ iostream input c++-faq istream

92
推荐指数
2
解决办法
2万
查看次数

getline(cin.name)被跳过

我从C++中的一个函数调用一个函数,该函数的getline(cin,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;
}
Run Code Online (Sandbox Code Playgroud)

c++ input function

4
推荐指数
1
解决办法
423
查看次数

标签 统计

c++ ×2

input ×2

c++-faq ×1

function ×1

iostream ×1

istream ×1