-2

I was trying to create a program to calculate the simplified version of a polynomial expression. I want to separate all of the variables, and constants (with plus signs) but my program seems to not be recognizing some of the plus signs in my string:

string al("2x+2+6y+8^7");
vector<string> variableStorage;
for (auto &c : al)
{
    static int count = 0;
    static int lastcount = 0;
    if(c == '+' || count == al.length()-1)
    {
        static int spot(0);
        variableStorage.push_back(al.substr(lastcount, count));
        lastcount = count+1;
        ++spot;
    }
    ++count;
}
for(auto c : variableStorage)
    cout << c << endl;

When I run this program, I get the following output:

    2x
    2+6y
    6y+8^7
    8^7

But my desired output is:

    2x
    2
    6y
    8^7

I tried checking my math for any mistakes, but it seems good as far as I can see.

2 Answers2

0

substr takes starting position and length. So you should be calling al.substr(lastcount, count-lastcount)

happydave
  • 7,127
  • 1
  • 26
  • 25
  • Ah, I must have been confused with java script. I assumed it was position to position. Anyways, I tried your code, but now I get 8^ instead of 8^7 – ProgrammingDreamer Mar 09 '14 at 03:48
0

Split the string (tokenize) at the +s

#include <string>
#include <vector>

using namespace std;

// This code from another SO question about splitting strings in C++
// http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c

template < class ContainerT >
void tokenize(const std::string& str, ContainerT& tokens,
              const std::string& delimiters = " ", bool trimEmpty = false)
{
   std::string::size_type pos, lastPos = 0;
   while(true)
   {
      pos = str.find_first_of(delimiters, lastPos);
      if(pos == std::string::npos)
      {
         pos = str.length();

         if(pos != lastPos || !trimEmpty)
            tokens.push_back(ContainerT::value_type(str.data()+lastPos,
                  (ContainerT::value_type::size_type)pos-lastPos ));

         break;
      }
      else
      {
         if(pos != lastPos || !trimEmpty)
            tokens.push_back(ContainerT::value_type(str.data()+lastPos,
                  (ContainerT::value_type::size_type)pos-lastPos ));
      }

      lastPos = pos + 1;
   }
};


int main( void )
{
    string al("2x+2+6y+8^7");
    vector<string> variableStorage;


    tokenize( al, viariableStorage );
    for(auto c : variableStorage)
        cout << c << endl;
    //Your items are in variableStorage at this point
    return( 0 );
}

The code above is not tested, it's late and I'm feeling lazy. I hope it gets the concept across.

JimR
  • 15,513
  • 2
  • 20
  • 26