我可以创建一个循环,直到`std :: cin`看到输入缓冲区中的`\ n`字符?

问题描述 投票:0回答:1

像这样的东西......

do{
    int x{};
    std::cin >> x;
}while(/*i want the condition mentioned here*/);

我的意思是,如果用户输入x并按Enter键,我希望循环结束。我能这样做吗?

c++
1个回答
4
投票

最常见的方法是读取整行,然后从该行提取数据。

也就是说,从“阅读事物直到遇到换行符”到更高级别的“读取所有内容”的观点发生了变化。

std::string line;
if (std::getline(std::cin, line))
{
    std::stringstream ls(line);
    int x = 0;
    while (ls >> x)
    {
        // Process x
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.