C++ 将输入字符*拆分为向量

C++ 将输入字符*拆分为向量,c++,vector,split,C++,Vector,Split,我创建了一个函数,该函数将字符*拆分为向量,但问题是,运行此方法后,该向量的所有元素都是输入行中的最后一个元素 例如: 输入:abc def ghi vector <const char*> dane; void split(char* str, char* sep){ char* cstr = str;//str.c_str konwersja str na char* char* current; current = strtok(cstr, sep);

我创建了一个函数,该函数将
字符*
拆分为
向量
,但问题是,运行此方法后,该
向量
的所有元素都是输入行中的最后一个元素

例如:

输入:
abc def ghi

vector <const char*> dane;
void split(char* str, char* sep){
    char* cstr = str;//str.c_str konwersja str na char*
    char* current;
    current = strtok(cstr, sep);
    string s;
    while(current != NULL){
        s = current;
        int foundF = s.find_first_not_of("-.\"-\\/!,`");
        int foundL =  s.find_last_not_of("-.\"-\\/!,`");
        if(foundL==string::npos)//find first or last zwrocilo nulla
            foundL = s.length();
        if(foundF==string::npos)
            foundF = 0;
        s = s.substr(foundF, foundL + 1);
        const char* c = s.c_str();
        dane.push_back(c);
        current=strtok(NULL, sep);
    }
}

int main(){
    char* c = new char[256];
    cin.getline(c,256);
    cout<<c<<endl;
    split(c, " ");
    for(int i  = 0; i < dane.size(); i++){
        cout<<dane.at(i)<<endl;
    }
    return 0;
}
向量:
ghi,ghi,ghi

vector <const char*> dane;
void split(char* str, char* sep){
    char* cstr = str;//str.c_str konwersja str na char*
    char* current;
    current = strtok(cstr, sep);
    string s;
    while(current != NULL){
        s = current;
        int foundF = s.find_first_not_of("-.\"-\\/!,`");
        int foundL =  s.find_last_not_of("-.\"-\\/!,`");
        if(foundL==string::npos)//find first or last zwrocilo nulla
            foundL = s.length();
        if(foundF==string::npos)
            foundF = 0;
        s = s.substr(foundF, foundL + 1);
        const char* c = s.c_str();
        dane.push_back(c);
        current=strtok(NULL, sep);
    }
}

int main(){
    char* c = new char[256];
    cin.getline(c,256);
    cout<<c<<endl;
    split(c, " ");
    for(int i  = 0; i < dane.size(); i++){
        cout<<dane.at(i)<<endl;
    }
    return 0;
}
vectordane;
无效拆分(字符*str,字符*sep){
char*cstr=str;//str.c_str konwersja str na char*
字符*电流;
电流=strtok(cstr,sep);
字符串s;
while(当前!=NULL){
s=电流;
int foundF=s.find_first_not_of(“-.\”-\\/!,`”);
int foundL=s.find\u last\u not\u of(“-.\”-\\/!,`”);
if(foundL==string::npos)//查找第一个或最后一个zwrocilo nulla
foundL=s.长度();
if(foundF==string::npos)
foundF=0;
s=s.substr(foundF,foundL+1);
const char*c=s.c_str();
丹麦。推回(c);
当前=strtok(空,sep);
}
}
int main(){
char*c=新字符[256];
c.getline(c,256);
库特
当然,这可能会导致您得到什么,因为
s.c_str()
始终可以指向同一个位置。就我而言,这仅仅取决于
std::string
的实现-您正在存储和使用c const char指针
string::c_str()
在特定字符串实例无效后返回(由于赋值运算符),我相信您的程序会调用未定义的行为

将要进行的更改:

vector<string> dane;
然后将下一行改为

dane.push_back(s);

现在您将拥有子字符串的副本(而不是指向它们的悬空指针),这将输出正确的结果。

也许这个问题可以帮助您:Sidenote的可能重复:为什么要使用全局变量?另外,请注意常量的正确性。
无效拆分(常量char*str,常量char*sep,vector&dane)
会更好,然后将
dane
作为
main()
的局部变量。
dane.push_back(s);