gpt4 book ai didi

c++ 输入一个字符串——不是用 getline() 而是用 cin

转载 作者:行者123 更新时间:2023-11-28 06:48:02 26 4
gpt4 key购买 nike

输入带空格的字符串!

这是我的想法:

string name;
std::cout << "Please enter your full name: ";
std::cin >> std::noskipws;
while (std::cin >> name >> std::ws) {
full_name += name + " ";
}

假设您的名字是 Bill Billy Bobby Bronson Billson。

或者可能是添加:

if (name == "\n")
break;

对于 getline(),它是一条语句。但是,出于研究原因,我不想使用 getline()。

可以吗?

更新:

如果我尝试我的代码,无论我更改什么,我都会得到一个无限循环。

最佳答案

我不明白你为什么真的想这样做,但是,是的,这是可能的。

std::string

operator>> 读取输入字符,直到遇到空白字符。流有一个 ctype 方面,用于确定字符是否为空格。

在这种情况下,您需要一个\n 分类为空白的ctype 方面。

struct line_reader: std::ctype<char> {
line_reader(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table() {
static std::vector<std::ctype_base::mask>
rc(table_size, std::ctype_base::mask());

rc['\n'] = std::ctype_base::space;
return &rc[0];
}
};

您将包含该 ctype 方面的语言环境实例注入(inject)您的输入文件:

int main() {
std::vector<std::string> lines;

// Tell the stream to use our facet, so only '\n' is treated as a space.
std::cin.imbue(std::locale(std::locale(), new line_reader()));

// to keep things at least a little interesting, we'll copy lines from input
// to output if (and only if) they contain at least one space character:
std::copy_if(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, "\n"),
[](std::string const &s) {
return s.find(' ') != std::string::npos;
});
}

这里我使用了 std::istream_iterator,它使用指定类型的提取运算符(在本例中为 std::string)来读取数据。

关于c++ 输入一个字符串——不是用 getline() 而是用 cin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24582912/

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