c++ - 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!
解决方案
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;
}
推荐阅读
- angular - Prime NG 的可编辑表上的奇怪行为
- perl - Perl:Windows 与 Unix 上的 exec()
- uilocalnotification - iOS 13本地通知未发送
- javascript - Alexa 技能不会将数据发送到 firebase (Cloud Firestore)
- javascript - 如何在 amcharts 中设置静态默认时区
- python - 如何在Django的views.py中调用models.py中的特定字段
- javascript - 如何为 nodejs/node 源代码生成 package.json 文件?
- flutter - 在 Flutter 的本地文件中保存 DateTime 类型
- c++ - 使用 cudaMemcpy 时出现分段错误
- asp.net-core - 尝试激活“BService”时无法解析“AService”类型的服务