用多定界符从C ++中的文件中分割一行,然后将一些字符存储在变量中

问题描述 投票:-1回答:1

我如何从格式为[i:20]的文件中拆分一行,然后将'i'和'20'存储在变量中,我尝试使用:

while(getline(myFile, line){
 getline (myFile,'[');
      getline (myfile,' ');
      getline (myfile,cmd);
      getline (myfile,':');
      getline (myFile,' ');
getLine(myFile, val);
      getline (myfile,']');
}

但效果不佳,在getline (myFile,'[');行上给我错误。任何帮助表示赞赏,谢谢

c++ file delimiter
1个回答
0
投票

您可以在读完该行后从行中解析出这些部分。

例如:

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

using std::cout;
using std::regex;
using std::regex_search;
using std::smatch;
using std::string;
using std::tuple;

static tuple<string, string> parse(string line) {
    auto re = regex(R"ere(^\[ *([^: ]*) *: *([^] ]*) *]$)ere", regex::extended);
    smatch sm; 
    regex_search(line, sm, re);
    if (sm.size() != 3) {
        cout << "err: " << sm.str(0) << "\n";
        return {"", ""};
    }   
    return {sm.str(1), sm.str(2)};
}

int main() {
    string line = "[ i : 20 ]";
    auto [cmd, val] = parse(line);
    cout << "cmd:" << cmd << "\n";
    cout << "val:" << val << "\n";
}
© www.soinside.com 2019 - 2024. All rights reserved.