试图将字符串添加到矢量

时间:2016-10-28 04:20:48

标签: c++ vector token

我正在尝试创建一个函数,该函数将读取可能包含字母,运算符或数字的字符串,并将它们放入向量中。我正在努力弄清楚如何将多位数字放入向量中的一个位置。这就是我所拥有的。任何帮助将不胜感激

vector <string> getTokens (string token){   

    int a = (int) token.length();
    string temp;
    vector <string> numbers;

    char t; 

    for (int i =0; i <a; i++){

        t = token[i];

        if (isdigit(t)){ //should i be using a while loop?

            numbers.at(i).push_back(t);
            //seg fault here
        }

        else if (t=='+' || t=='-' || t=='/' || t=='*' || t=='^'){   
            cout << "operator" <<endl;
            string tt;
            tt+=t;
            numbers[i] = tt;
        }       


        else if (t=='(' || t==')'){
            string tt;
            tt += t;
            numbers[i] = tt;
        }

2 个答案:

答案 0 :(得分:3)

从你的代码看起来我认为你正在写一个词法分析器/标记器。

这样做的一种方法是:

#include <string>
#include <iostream>
#include <vector>
std::vector <std::string> getTokens (std::string token){   

        std::vector<std::string> numbers;
        std::string temp;

        //iterators to begin and end of input
        std::string::const_iterator iter = token.begin();
        std::string::const_iterator end = token.end();

        //keep looping until we have seen each character
        while(iter < end){
            //if is a digit
            if(std::isdigit(*iter)){
                //loop until the current char is no longer a digit
                while(std::isdigit(*iter)){
                    //collect the digit into temp
                    temp+=*iter;
                    //advacnce the iterator
                    ++iter;
                }
                //store the resulting string
                numbers.push_back(temp);
                //clear temp
                temp.clear();
            }
            //you could also check for other types of characters with else if(...) cases
            else{
                //discard all non numbers

             std::cout<<*iter<<" is not a number... discarding!"<<std::endl; 
             ++iter;//make sure to adavnce the iterator
            }

        }
        return numbers; 
}

int main(int argc, char** argv){
    std::string input = "123a123";

    std::vector<std::string> out = getTokens(input);

    for(auto&& x: out){
     std::cout<<x<<std::endl;   
    }

}

输出:

  

a不是数字......丢弃!

     

123

     

123

LIVE DEMO!

您正在做一些会导致代码出现问题的事情:

当您在此处致电numbers时,at()为空,您收到了段错误:

numbers.at(i).push_back(t);
            //seg fault here

如果您需要进一步解释我提供的代码,请告诉我。

答案 1 :(得分:0)

谢谢大家的帮助!我终于明白了。

for (int i =0; i <a; i++){

            t = token[i];
            if(isdigit(t)){
            string tt;
            while (isdigit(token[i])){
                tt+= token[i];              
                i++;                
            }
            numbers.push_back(tt);
        }

这至少解决了数字问题