parsing a line

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mickey0
    New Member
    • Jan 2008
    • 142

    parsing a line

    hello, I have to parsing a string like this:
    char * = "10 20 30 40";
    and put its number into a vector<double>
    I thought to use strchr() and atof() and it's seems ok but to say the truth the line could be at times a little different:
    char * = "10 20 30 40 ";
    char * = "10,20,30,4 0";
    char * = "10, 20,30, 40 ";
    char * = "10 20,30 40 ";
    all these above are valid line; instead this isn't':
    char * = "10 20 30 40,"; (comma ate the end isn't accetable)
    The number in the string must have a separtor: it could be a white space (or \t) or other (e.g. a comma); Can I work with strchr and atof.....or Do I need a little parser? I tried with the first way but the code seems not good....any suggest? (to note: I need to write the code on my own and not to use parsers generators)....

    thanks.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    I would use strtod rather than atof. strtod has the added advantage of returning a pointer to where it finished converting within the string which makes parsing a bit different.

    Also if you look in the "Howtos" section of this site, available on the menu above you will find several good articles on parsing text data from a file.

    Comment

    • mickey0
      New Member
      • Jan 2008
      • 142

      #3
      hello I read th tutorial but I don't sure it can be solve problems like these:

      ,10,20,30 //this line is wrong for the ',' at begin
      10,,20,30 //wrong
      10,20,30, //wrong

      Is there any hints for this, please? thanks.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Check the character you are currently on before you start parding, for instance at the beginning of the line check you have a digit, use the function IsDigit (defined in ctype.h along with a whole load of other Is... functions). When you get to a comma check the following character is a digit.

        Work out what the rules governing the format of your data lines is and then write and algorithm that enforces that format.

        Comment

        • mickey0
          New Member
          • Jan 2008
          • 142

          #5
          sorry if you read the code before, you can see that I'm using
          Code:
          		
          		stm.str(line);		
          		while(true) {
          			stm >> intValue; //1
          In that code if between two number there is comma (eg 1000,30), the //1 fails because it doens't find a white space....The problem is more complex: isdigit can be used only to check the first character...... but it doens't solve the other problems.....

          Comment

          Working...