簡體   English   中英

如何讀入 c++ stringstream 的第三個字

[英]How to read in the third word of c++ stringstream

我收到了一份文件,我需要從中讀取某些重要信息到我的 C++ 程序中。 這些信息以下列格式給出:

關鍵字:VALUE_OF_KEYWORDS_TYPE

其中VALUE_OF_KEYWORDS_TYPE通常包含一個 integer 值。 我使用以下方案將此值讀入我的程序:

int variable_to_store_value = 0;
std::string content_of_line = "";
std::getline(file,content_of_line);
std::stringstream stream(content_of_line);
std::string threshold;
stream >> threshold >> threshold >> variable_to_store_value ;

使用閾值變量對我來說似乎有點可擴展,但我不確定解決這個問題的最正確方法是什么......另外讓我知道,如果在這些事情的運行時間方面有更有效的方法。 非常感謝您嘗試幫助我解決我的問題!

使用threshold變量對我來說似乎有點可擴展,但我不確定解決這個問題的最正確方法是什么......

我建議完全擺脫threshold變量,而是使用stream.ignore()方法來跳過你不想要的東西,例如:

#include <sstream>
#include <string>
#include <limits>

std::string content_of_line;
if (std::getline(file, content_of_line)) {
    std::istringstream stream(content_of_line);
    stream.ignore(std::numeric_limits<std::streamsize>::max(), ':');
    int variable_to_store_value = 0;
    if (stream >> variable_to_store_value) {
        // use variable_to_store_value as needed...
    }
}

或者,您也可以去掉stream變量:

#include <limits>

if (file.ignore(std::numeric_limits<std::streamsize>::max(), ':')) {
    int variable_to_store_value = 0;
    if (stream >> variable_to_store_value) {
        // use variable_to_store_value as needed...
    }
    file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

暫無
暫無

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

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