簡體   English   中英

從文件中的一行讀取特定數據 - C++

[英]Reading specific data from a line in a file - C++

我有一個像這樣划分的.txt文件:

(P1, 3): (E10, E20, E1, E3)
(P2, 2): (E10, E20, E2,  E5)
(P3, 2): (E10, E20)

我只想將每行的數字保存在一個數組中。 例如:第一個是 [1,3,10,20,1,3]。 我怎樣才能做到這一點?

使用ifstream逐行遍歷文件。

將字符串讀取到 std::string 后,使用正則表達式搜索來查找新讀取的字符串中出現的數字。

您要用於提取字符串中所有數字的正則表達式如下:

https://regex101.com/r/yWJp5p/3

使用示例:

#include <regex>
#include <iostream>
#include <string>

std::vector<std::string> fetchMatches(std::string str, const std::regex re) {
    std::vector<std::string> matches;
    std::smatch sm; // Use to get the matches as string

    while (regex_search(str, sm, re)) {
        matches.push_back(sm.str());
        str = sm.suffix();
    }

    return matches;
}

int main() {
    std::string example_input = "(P1, 3): (E10, E20, E1, E3)";

    std::regex re{"\\d+"};

    auto matches = fetchMatches(example_input, re);

    for (const auto& match : matches) {
        std::cout << match << std::endl;
    }

    return 0;
}

有多種解決方案。 解釋解決方案之一。

使用C的 isDigit 和strtol函數。

char *str = "(P1, 3): (E10, E20, E1, E3)", *p = str;
while (*p) {
    if ( isdigit(*p)) {
        long val = strtol(p, &p, 10); 
        printf("%ld\n", val);
    } else {
        p++;
    }
}

注意:如果文件有負數,則需要檢查。

只需在 if 條件中添加((*p=='-'||*p=='+') && isdigit(*(p+1)))

暫無
暫無

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

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