读取由空格或换行符分隔的输入...?

2021-12-21 00:00:00 input c++

我正在从标准输入流中获取输入.比如,

I'm grabbing input from a standard input stream. Such as,

1 2 3 4 5

1
2
3
4
5

我正在使用:

std::string in;
std::getline(std::cin, in);

但这只是抓住了换行符,对吗?如何仅使用 iosteam、字符串和 cstdlib 获取输入是否由换行符或空格分隔?

But that just grabs upto the newline, correct? How can I get input whether they are separated by newline OR whitespace(s) using only iosteam, string, and cstdlib?

推荐答案

只需使用:

your_type x;
while (std::cin >> x)
{
    // use x
}

operator>> 默认会跳过空格.您可以链接事物以一次读取多个变量:

operator>> will skip whitespace by default. You can chain things to read several variables at once:

if (std::cin >> my_string >> my_number)
    // use them both

getline() 读取一行中的所有内容,无论它是空的还是包含数十个空格分隔的元素,都返回.如果您提供可选的替代分隔符 ala getline(std::cin, my_string, ' ') 它仍然不会执行您似乎想要的操作,例如标签将被读入 my_string.

getline() reads everything on a single line, returning that whether it's empty or contains dozens of space-separated elements. If you provide the optional alternative delimiter ala getline(std::cin, my_string, ' ') it still won't do what you seem to want, e.g. tabs will be read into my_string.

这可能不需要,但您可能很快会感兴趣的一个相当常见的要求是读取单个换行符分隔的行,然后将其拆分为组件...

Probably not needed for this, but a fairly common requirement that you may be interested in sometime soon is to read a single newline-delimited line, then split it into components...

std::string line;
while (std::getline(std::cin, line))
{
    std::istringstream iss(line);
    first_type first_on_line;
    second_type second_on_line;
    third_type third_on_line;
    if (iss >> first_on_line >> second_on_line >> third_on_line)
        ...
}

相关文章