如何将方程组成矩阵?

时间:2012-09-13 06:50:22

标签: c++ io c++11 tokenize

我正在研究一个解决多个方程的程序,但那并不重要。我遇到的麻烦就是解释方程式。

e.g。我有一个名为data.txt的文件,其内容如下:

2x - 5y + 3z = 10
5x + y - 2z = 4

我一直试图解释这个问题很长一段时间但没有成功,因为我认为C ++会有类似str.split()的东西。我想到的是一个包含这些内容的数组:

2 -5 3 10
5 1 -2 4

我该怎么办呢?

1 个答案:

答案 0 :(得分:-1)

vector>数据

逐行读取data.txt:string line

使用分隔符分隔线“\ t + - =”:向量标记

将令牌转换为数字格式:vector v

将v推送到data:data.push_back(v)

更新

vector<string> split(const string &s, const string &d)
{
    vector<string> t;
    string::size_type i = s.find_first_not_of(d);
    string::size_type j = s.find_first_of(d,i);
    while (string::npos != i || string::npos != j) {
        t.push_back(s.substr(i,j-i));
        i = s.find_first_not_of(d,j);
        j = s.find_first_of(d,i);
    }
    return t;
}

int main()
{
    vector<vector<double> > x;
    ifstream ifs("data.txt");
    string ls;
    while (getline(ifs,ls))
    {
        vector<string> ts = split(ls," \t+-=");
        vector<dobule> v;
        for (auto& s : ts)
            v.push_back( atof(s.c_str()) );
        x.push_back(v);
    }
    return 0;
}