簡體   English   中英

在最后一次出現定界符之后,std :: getline會跳過std :: cin的輸入,但不會跳過std :: istringstream的輸入

[英]std::getline skipping input from std::cin after last occurrence of delimiter, but not with input from std::istringstream

我需要閱讀一些由空格分隔的輸入,我用於此的主要結構是:

while(std::getline(std::cin, s, ' ')){
    std::cout << s << std::endl;
}

對於輸入:“這是一些文本”

S的輸出將是:“ this”,“ is”,“ some”,從而跳過最后一個空格之后的最后一個輸入。

我也想在程序中包含最后的輸入內容,因此我去尋找解決方案並找到了以下內容:

while (std::getline(std::cin, line)) {
    std::istringstream iss(line);

    while (std::getline(iss, s, ' ')) {
        std::cout << s << std::endl;
    }
}

對於輸入:“這是一些文本”

S的輸出將是:“ this”,“ is”,“ some”,“ text”,這正是我想要的。

我的問題是:為什么在最后一次出現分隔符之后從帶有分隔符的std :: cin讀取會跳過輸入,但是從std :: istringstream讀取卻不會呢?

我的問題是:為什么在最后一次出現分隔符之后從帶有分隔符的std::cin讀取會跳過輸入,但是從std::istringstream讀取卻不會呢?

沒有。

在第一個示例中:

while(std::getline(std::cin, s, ' ')){
    std::cout << s << std::endl;
}

您是專門從換行符中讀取由單個空格分隔的項目。 因為該行(表面上)以換行符結束,所以它將永遠不會完成從輸入字符串中的提取,因為它期望是' '或EOF。

在第二個示例中:

while (std::getline(std::cin, line)) {
    std::istringstream iss(line);

    while (std::getline(iss, s, ' ')) {
        std::cout << s << std::endl;
    }
}

前一陣子的std::getline將從示例句中刪除換行符。 然后根據一些基本規則提取項目。

以下是規則(來自cppreference)

Extracts characters from input and appends them to str until one of the following occurs (checked in the order listed)
    a) end-of-file condition on input, in which case, getline sets eofbit.
    b) the next available input character is delim, as tested by Traits::eq(c, delim), in which case the delimiter character is extracted from input, but is not appended to str.
    c) str.max_size() characters have been stored, in which case getline sets failbit and returns.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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