0

I'm working on a program to solve multiple equations, but that's not relevant. What I'm having trouble with is interpreting equations.

e.g. I have a file called data.txt whose contents are as following:

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

I've been trying to interpret this for quite a while but didn't succeed as I thought C++ would have something like str.split(). What I had in mind was an array with these contents:

2 -5 3 10
5 1 -2 4

How can I do this please?

argoneus
  • 1,097
  • 2
  • 13
  • 24
  • You could copy the source strings into new string objects, skipping any character that is not a digit or + or -. (This assumes the order of the variables x, y and z is the same in every equation.) – jogojapan Sep 13 '12 at 06:53
  • 2
    possible duplicate of [Splitting a string in C++](http://stackoverflow.com/questions/236129/splitting-a-string-in-c) – Mat Sep 13 '12 at 06:53
  • @Mat I've read that thread but couldn't really understand :(. Also, I know I'm missing a 3rd equation, it's intentional – argoneus Sep 13 '12 at 06:55
  • Assuming there would always be an integer in front of a variable, the following sed command would work. It could easily be adapted for use with C++ regex `'s/[ =+]//g;s/[A-z]/ /g'`. From there you can use your favorite parsing technique, be it getline w/ stringstream, cin, ifstream, etc. – willkill07 Sep 13 '12 at 08:27

1 Answers1

-1

vector > data

read data.txt line by line: string line

split line using delimiter " \t+-=": vector tokens

convert tokens to numeric format: vector v

push v to data: data.push_back(v)

Update:

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;
}
hjbabs
  • 27
  • 3