如何在C ++中读取空格分隔的输入,我们不知道输入数量

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

我已经读取了如下数据

7
1 Jesse 20
1 Jess 12
1 Jess 18
3 Jess
3 Jesse
2 Jess
3 Jess

这里7是输入行数,我必须读取c ++中用空格分隔的输入,如果不知道如何分隔它们,我该如何读取这些输入。该行包含字符串和整数。

c++ cin getline
1个回答
0
投票

这里是一个示例,它使用operator>>std::string

int x;
std::string name;
int y;
int quantity;
std::cin >> quantity;
for (int i = 0; i < quantity; ++i)
{
    std::cin >> x;
    std::cin >> name;
    std::cin >> y;
}

以上内容适用于具有3个字段的所有行,但不适用于没有最后一个字段的行。因此,我们需要增强算法:

std::string text_line;
for (i = 0; i < quantity; ++i)
{
    std::getline(std::cin, text_line); // Read in the line of text
    std::istringstream  text_stream(text_line);
    text_line >> x;
    text_line >> name;
    // The following statement will place the text_stream into an error state if
    // there is no 3rd field, but the text_stream is not used anymore.
    text_line >> y;
}

根本原因是缺少的第三字段元素将导致第一个示例不同步,因为它将读取第三字段下一行的第一列。

第二个代码示例通过一次读取一行进行校正。输入操作仅限于文本行,并且不会超出文本行。

© www.soinside.com 2019 - 2024. All rights reserved.