If语句不识别加号

If Statement Not Recognizing Plus Sign

本文关键字:识别 语句 If      更新时间:2023-10-16

我试图创建一个程序来计算一个多项式表达式的简化版本。我想分开所有的变量,和常数(加号),但我的程序似乎不能识别一些加号在我的字符串:

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;

当我运行这个程序时,得到以下输出:

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

但是我想要的输出是:

    2x
    2
    6y
    8^7

我试着检查我的数学是否有错误,但就我所见,它似乎很好。

+ s处拆分字符串(tokenize)

#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 );
}

上面的代码没有测试,很晚了,我觉得很懒。

获取起始位置和长度。所以你应该调用al.substr(lastcount, count-lastcount)