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

How to read space separated input in C++ When we don't know the Number of input

本文关键字:输入 我们 不知道 分隔 C++ 空格 读取      更新时间:2023-10-16

我已经读取了类似以下的数据

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

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

以下是一个使用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;
}

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

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

相关文章: