Seg Fault使用Copy()和Istream_Iterator将字符串解析为向量成员

时间:2017-06-10 19:07:15

标签: c++ string vector

我有一些看起来像这样的输入:

CH4
9_site_nonpolar
66
#TEMP #PRES #V #DENSITY
115.0 00.1 10186012.74173 0.00017
145.0 00.1 12709964.99224 0.00014
175.0 00.1 15482213.03440 0.00011
205.0 00.1 18140114.97385 0.00010
...

数字66是指数据行的数量(即#TEMP...行以下的数据行。)

我正在尝试接受此输入,忽略前两行,存储第三行,忽略第四行,然后将其余行解析为字符串向量。下面的代码是我的尝试,但是当我尝试访问向量this_line的成员时,它会出现段错误。

我对C ++比较陌生,并且一直很难调试它。我认为问题出在copy()行(我得到here;)两个cout语句打印到stdout然后程序失败。

代码中的向量all_runs的类型为vector<vector<run>>,其中run只是struct我用来保存这些变量。外部向量表示程序作为输入的每个文件,而内部向量用于保存数据行中的信息(例如115.0 00.1 10186012.74173 0.00017。)

    string file_name,
           line;
    for(int i = 1;i < argc;i++)
    {
        int j = 0;
        file_name = argv[i];
        ifstream input(file_name);
        input.ignore();
        input.ignore();
        int num_runs = atof(line.c_str());
        input.ignore();
        if(input.is_open())
        {
            while(getline(input,line))
            {
                vector<string> this_line;
                istringstream iss(line);
                //copy the numbers of interest from the line into the vector this_line
                cout << "hello"<< endl;
                copy(
                        istream_iterator<string>(iss),
                        istream_iterator<string>(),
                        back_inserter(this_line)
                );
                cout << "hi again" << endl;
                auto &ref = (all_runs[i-1])[j];//make current run a ref to clean up the code a bit
                ref.temperature = atof(this_line[0].c_str());
                ref.pressure_atm = atof(this_line[1].c_str());
                ref.simulation_V = atof(this_line[2].c_str());
                ref.density = atof(this_line[3].c_str());
                if(j == (num_runs - 1))
                    break;
                else
                    j++;
            }
        }
        input.close();
    }

感谢您的时间和任何可能提供的帮助!

0 个答案:

没有答案