文本逐行解析,循环扫描分组内容

时间:2017-11-26 01:40:09

标签: c++ c++11 visual-c++

在txt文件中,种群0和1各自有自己的参数值,格式如下:

population 0
gK 9
gNa 35
gL 0.1

population 1 
gK 9
gNa 35
gL 0.1

使用ifstream加载文件,使用getline和stringstream进行解析。

我尝试制作一个循环,以便在遇到包含“population 0”的行时,根据模板“contents>> param_name>> param_val”逐行读取其参数, 参数名称与预期的字符串进行比较,其值进入相应的指针数组(即:填充0,gK = 9进入gK [0])

到达最后一个预期参数,或到达下一个群体(i + 1),跳转到文本中寻找下一个群体(i + 1)。

void Parameters::Initialize(ifstream & pfile) {
 stringstream char_content;
 string temp;
 string line;
 string param_name;
 double param_val{ 0 };

 while (getline(pfile, line)) {

    stringstream contents(line);


    if (contents.rdbuf()->in_avail() == 0) { // if 
        continue;
    }

    if (!(contents >> param_name >> param_val)) { 
        printf("error reading line from file. position: file %s line %d\n", __FILE__, __LINE__);
        throw "error reading file";
    }


for (int i { 0 }; i <= 2; ++i) { 

        if ((param_name.compare("Population") == 0) && (param_val == i)) { //if condition satisfied, get subsequent lines up to next population

        if (param_name.compare("gK") == 0); gK[i] = param_val;
        if (param_name.compare("gNa") == 0); gNa[i] = param_val;
        if (param_name.compare("gL") == 0); gL[i] = param_val;

        if ((param_name.compare("Population") == 0) && (param_val == i + 1)) continue;
        }
    }
}
}

int main (){
    cin >> file; // .txt file
    std::ifstream paramFile(file);

    P.Initialize(paramFile);
}

如果有人可以帮助制作正常版本,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

阅读stringstream后,您必须继续阅读该文件以获取gK等的值。

param_val声明为int。这样您就可以将param_valint计数器进行比较。

param_name与小写"population"

进行比较

gK等可以声明为std::vector,使用push_back方法将值添加到vector

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>

using namespace std;

std::vector<double> gK, gNa, gL;

void Initialize(ifstream & pfile) 
{
    string line, param_name;
    int param_val;
    int counter = 0;
    while(getline(pfile, line)) 
    {
        stringstream contents(line);

        if(contents.rdbuf()->in_avail() == 0) 
            continue;

        if(contents >> param_name >> param_val)
        {
            if(param_name == "population" && param_val == counter)
            {
                double val;
                pfile >> line >> val;
                gK.push_back(val);
                if(line != "gK") cout << "error\n";

                pfile >> line >> val;
                gNa.push_back(val);
                if(line != "gNa") cout << "error\n";

                pfile >> line >> val;
                gL.push_back(val);
                if(line != "gL") cout << "error\n";

                counter++;
            }
        }
    }

    for(int i = 0; i < counter; i++)
    {
        cout << "population " << i << "\n";
        cout << "gK " << gK[i] << "\n";
        cout << "gNa " << gNa[i] << "\n";
        cout << "gL " << gL[i] << "\n";
    }
}