首页 > 解决方案 > C++“noskipws”没有按预期工作,如何正确允许字符串中的空格?

问题描述

我希望能够输入一个完整的字符串,包括空格,然后打印该字符串。

为什么这段代码的行为不符合我的预期?

代码

#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << "Enter your name:\n";
    string name;
    cin >> noskipws >> name;
    cout << "Hello, " << name << "!";
    return 0;
}

输出

 Enter your name:
>tes test test
 Hello, tes!

标签: c++

解决方案


noskipws阻止流在读取值之前跳过前导空格。当它在一个单词operator>>到达空格时仍然会停止阅读。

如果要从控制台读取整行,请使用std::getline()代替operator>>

#include <iostream>
#include <string>

int main()
{
    std::cout << "Enter your name:\n";
    std::string name;
    std::getline(std::cin, name);
    std::cout << "Hello, " << name << "!";
    return 0;
}

推荐阅读