1

I have created function that splits the char* into vector but the problem is that after running this method all elements of this vector are the last element in the input line.

Example:

input:abc def ghi

vector: 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;
}
user2344333
  • 147
  • 1
  • 1
  • 9
  • Maybe this question can help you: http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c – Wayne Uroda May 11 '13 at 07:46
  • possible duplicate of [Splitting string into a vector of words](http://stackoverflow.com/questions/8425214/splitting-string-into-a-vectorstring-of-words) – user93353 May 11 '13 at 07:48
  • Sidenote: why are you using a global variable? Also, pay attention to const correctness. `void split(const char *str, const char *sep, vector &dane)` would be better, then have `dane` as a variable local to `main()`. –  May 11 '13 at 07:58

1 Answers1

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

Sure this may result in what you got, since s.c_str() can always point to the same location. As far as I'm concerned, this merely depends on the implementation of std::string - you're storing and using the C const char pointer string::c_str() returns after the particular string instance has been invalidated (as a result of the assignment operator) - I believe your program invokes undefined behavior.

Changes to be made:

vector<string> dane;

then remove

const char* c = s.c_str();

then change the next line into

dane.push_back(s);

and now you will have copies of substrings (as opposed to dangling pointers to them), and this will output the correct result.