我正在尝试创建一个函数,该函数将读取可能包含字母、运算符或数字的字符串并将它们放入 vector 中。我很难弄清楚如何将多位数字放在 vector 中的一个位置。这就是我所拥有的。任何帮助将不胜感激
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;
}
最佳答案
从您的代码来看,我认为您正在编写词法分析器/分词器。
一种方法是:
#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 is not a number... discarding!
123
123
您正在做一些会导致您的代码出现问题的事情:
您遇到段错误是因为当您在此处调用 at()
时 numbers
为空:
numbers.at(i).push_back(t);
//seg fault here
如果您需要进一步解释我提供的代码,请告诉我。
关于c++ - 试图将字符串添加到 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40297989/