Thread: Please help me with parsing numbers form a file

  1. #1
    Registered User
    Join Date
    Jul 2007

    Please help me with parsing numbers form a file


    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:

    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.......
        ifstream file;"1160_term_project_data.txt");
        int coef;
        int power;
        char ch;
            coef = 0;
            power = 0;
                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;
                        power = 1;
            if(coef != 0)
                cout << "Coefficient: " << coef << " Power: " << power << endl;
    I already tried .get(), .unget(), .peek() in the fstrem library, but still can't get what I want.

    Am I on the right track, or is there any other ways to do it? Thx.

  2. #2
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Assuming you don't need to check for data validity and are always presented with a well-formed file, you can iterate through ";" characters and extract exponents by reading the character after "^" and coefficients by reading every character between the last exponent and the next "^".

    Or so I seem to think from a diagonal reading of your post.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  3. #3
    Registered User
    Join Date
    May 2006
    You should use boost spirit.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  3. Parsing a flat file to a SQl Server database?
    By Michael71 in forum C Programming
    Replies: 0
    Last Post: 01-16-2007, 12:45 PM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM