I’m converting a string to char array and than back to a string and into a vector.
When I’m trying to print I’m getting this:
this
is
the
sentence iuִִ[nu@h?(h????X
and much more. This is the code:
int main(int argc, char *argv[]){
string s ="this is the sentence";
char seq[sizeof(s)];
strcpy(seq, "this is the sentence");
vector<string> vec = split(seq);
printWords(vec);
return 0;
}
And this is the func.cpp file. One function splits the char to string vector, the other is printing:
vector<string> split(char sentence[]){
vector<string> vecto;
int i=0;
int size= strlen(sentence);
while((unsigned)i< size){
string s;
char c =' ';
while(sentence[i]!=c){
s=s+sentence[i];
i+=1;
}
vecto.push_back(s);
i+=1;
}
return vecto;
}
void printWords(vector<string> words){
int i=0;
while ((unsigned)i<words.size()){
string s = words.at(i);
cout << words.at(i) << endl;
i+=1;
}
}
After understanding the answer above, try a less error-prone style, something more like this (C++11):