簡體   English   中英

當我們不知道輸入的數量時,如何在 C++ 中讀取空格分隔的輸入

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM