相关疑难解决方法(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万
查看次数

标签 统计

c++ ×1

c++-faq ×1

input ×1

iostream ×1

istream ×1