gpt4 book ai didi

c++ - C++ “noskipws”无法正常工作,如何在字符串中正确允许空格?

转载 作者:行者123 更新时间:2023-12-01 15:13:32 34 4
gpt4 key购买 nike

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

为什么此代码不符合我的预期?

代码

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

关于c++ - C++ “noskipws”无法正常工作,如何在字符串中正确允许空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59904251/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com