C++ "noskipws"没有按预期工作,如何正确允许字符串中的空格?

C++ "noskipws" is not working as expected, How to properly allow whitespace in string?

本文关键字:何正确 字符串 空格 noskipws 工作 C++      更新时间:2023-10-16

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

为什么这段代码的行为不像我预期的那样?

法典

#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!
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;
}

您可以定义一个帮助程序类,为自己提供看起来像操纵器的东西(如果这是您要使用的语法(。

struct Getline {
std::string &s_;
Getline(std::string &s) : s_(s) {}
friend auto & operator >> (std::istream &&is, Getline &&g) {
return std::getline(is, g.s_);
}
};

然后你可以像这样使用它:

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