【问题标题】:How to read space separated input in C++ When we don't know the Number of input当我们不知道输入的数量时,如何在 C++ 中读取空格分隔的输入
【发布时间】:2020-02-22 17:40:13
【问题描述】:

我已阅读如下数据

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

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

【问题讨论】:

  • 一种方法是getline,然后有一个函数将行解析为stringstream。
  • 在互联网上搜索“c++ 读取空格分隔值”和“c++ 读取 csv”。始终先搜索互联网。

标签: c++ cin getline


【解决方案1】:

这是一个例子,它使用了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;
}

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

第二个代码示例通过一次读取一行来进行更正。输入操作仅限于文本行,不会越过文本行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-30
    • 2012-10-17
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    相关资源
    最近更新 更多