Hi,
I am doing my assignment, I need to parse the coefficient and exponent of each term from the polynomials in a file.
A polynomial in the input file will end with a semicolon ;. In the following example there are 4 polynomials:
x-1;x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1;2x^2-x+1;-x^3+x;
I am not allowed to use string to read the input, and I have to get them on the fly when I read the file.
Here is my attempt, but get bad results.......
I already tried .get(), .unget(), .peek() in the fstrem library, but still can't get what I want.Code:ifstream file; file.open("1160_term_project_data.txt"); int coef; int power; char ch; while(!file.eof()) { coef = 0; power = 0; if(isdigit(file.peek())) file >> coef; ch = file.get(); if(ch == '-' && isdigit(file.peek())) { file >> coef; coef *= -1; ch = file.get(); } if(ch == '+' && file.peek() == 'x') coef = 1; else if(ch == '-' && file.peek() == 'x') coef = -1; else if(ch == 'x') { if (coef == 0) coef = 1; if(file.peek() == '^') { ch = file.get(); file >> power; } else { power = 1; } } if(coef != 0) cout << "Coefficient: " << coef << " Power: " << power << endl; } file.close();
Am I on the right track, or is there any other ways to do it? Thx.