C++ "noskipws"没有按预期工作,如何正确允许字符串中的空格?
C++ "noskipws" is not working as expected, How to properly allow whitespace in string?
我希望能够输入一个完整的字符串,包括空格,然后打印该字符串。
为什么这段代码的行为不像我预期的那样?
法典
#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;
}
相关文章:
- 如何使用Luacneneneba API正确读取字符串和表参数
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- C++ "noskipws"没有按预期工作,如何正确允许字符串中的空格?
- 如何正确解析子字符串,以便它们对我的新手计算器有效?
- 如何从标准::string_view正确创建标准::字符串?
- 如何检查字符串是否正确以将其转换为 int?
- 用于从 ANSI 字符串转换为 std::basic_string <TCHAR>的正确函数声明
- 控制台未正确读取输入字符串
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 为什么要 boost::p roperty_tree::write_json() 将整数值转换为字符串?这是不正确的
- 无法使用substr和find正确解析带有空格的字符串
- 将字符串强制转换为GUID并不能得到正确的结果
- 交换两个字符串时访问正确的内存时,我遇到了分段错误
- C++-将对象(如字符串)映射到表中成员函数的正确方法
- MSVC UTF8字符串编码使用了不正确的代码点
- std::smatch str() 未返回正确的字符串
- 如何正确实现 std::all_of 函数来验证字符串的一部分?
- 简单的字符串替换给出错误,尽管参数正确