2013-05-11 83 views
0

我已經創建了將char*拆分爲vector的函數,但問題是運行此方法後,此vector的所有元素都是輸入行中的最後一個元素。將輸入字符*拆分爲向量

例子:

輸入:abc def ghi

載體: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; 
} 
+0

也許這個問題可以幫助你:http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c – 2013-05-11 07:46:23

+0

可能的重複[將字符串拆分成矢量的字](http://stackoverflow.com/questions/8425214/splitting-string-into-a-vectorstring-of-words) – user93353 2013-05-11 07:48:39

+0

旁註:爲什麼你使用全局變量?另外,要注意const的正確性。 'void split(const char * str,const char * sep,vector &dane)''會更好,然後'dane'作爲main()的局部變量。 – 2013-05-11 07:58:47

回答

3
const char* c = s.c_str(); 
dane.push_back(c); 

當然這可能導致你得到了什麼,因爲s.c_str()總是可以指向同一個位置。就我而言,這隻取決於std::string的實現 - 您正在存儲並使用C const char指針string::c_str()在特定字符串實例失效後(作爲賦值運算符的結果)返回 - 我相信你的程序調用未定義的行爲。要進行

變化:

vector<string> dane; 

然後取出

const char* c = s.c_str(); 

然後下一行變成

dane.push_back(s); 

,現在你將有子的拷貝(而不是懸掛指針),這將輸出正確的結果。