Some string confusions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • KanchanG
    New Member
    • Oct 2007
    • 2

    #1

    Some string confusions

    Hi, I'm new here and relatively new to c++ as well. I'm trying to write a function which will solve a quadratic equation. The progran needs to distinguish which coefficient is a, b and c. The quadratic is on the command line at argv[2].

    So I decided to split the string (quadratic) up to the x

    e.g. 4x^2 + 3x + 5

    I want the code to read up to x^2 and place the value into a vector. It will then ignore everything until the +/- and then read the value until the x and place that into a vector; once again ignore everything until it passes the +/- and then read the c constant and place that into a vector.
    I would prefer to use an array to store the a, b and c values. Can anyone help me with a code to run through the string and extract the required values?


    Another issue is this:
    Provided i can use an array, can i initialize the array as follows:
    arr[0] = a
    arr[1] = b
    arr[2] = c
    where a, b and c can take any values as specified by the user?

    Any help would be greatly appreciated.
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    Vectors would be a mistake, because if a is a multidigit number, the code to transfer from the vector to an integer is more complex than to transfer from a string to an integer.

    You can use the strtok() C-string function to split up the input string. The code for this is kind of complicated, but there are good sites (cplusplus.com is the one I usually use) that explain it pretty well with examples.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      You could make a copy of the string and start a loop looking at copy[0]. Maje a decision on what it is and what to do with then erase copy[0]. The rest of the string will slide to the left so on the next cycle of your loop copy[0] will be the 2nd character of the origingal string. The loop continues until you have erases the entire copy.

      You might look up finite-state automaton, which is the mechanism used for this sort of thing.

      Yes, you can use an array to hold your coefficients. Just be aware that the type of the coefficients must match the element type of the array.

      Comment

      Working...