[英]How to read space separated input in C++ When we don't know the Number of input
我已经阅读了如下数据
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;
}
根本原因是缺少第 3 个字段元素将导致第一个示例不同步,因为它将读取下一行的第 1 列作为第 3 个字段。
第二个代码示例通过一次读取一行来进行更正。 输入操作仅限于文本行,不会越过文本行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.