| | |
Splitting a string into tokens using strtok and string as parameter
Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved |
•
•
Join Date: Dec 2008
Posts: 57
Reputation:
Solved Threads: 0
I have got an example for cplusplus.com for converting a string into a char array so i can split in into tokens and adds to a vector and it works fine in the main method but if i try and create a separate function and pass a string as a parameter, the program crashes with no explanation. It compiles fine.
Have i created the function type correctly? I want to create a vector of strings so i can output each vector.
Have i created the function type correctly? I want to create a vector of strings so i can output each vector.
C++ Syntax (Toggle Plain Text)
// strings and c-strings #include <iostream> #include <cstring> #include <string> #include <vector> using namespace std; vector<string> SplitString (string aString) { vector<string> vec; char * cstr, *p; //string str ("Please split this phrase into tokens"); string str = aString; cstr = new char [str.size()+1]; strcpy (cstr, str.c_str()); // cstr now contains a c-string copy of str p=strtok (cstr," "); while (p!=NULL) { vec.push_back(p); p=strtok(NULL," "); } delete[] cstr; } int main () { std::vector<std::string> vec = SplitString("Please split this phrase into tokens"); for (std::vector<std::string>::size_type a = 0; a < vec.size(); ++a) { cout << vec.at(a) << '\n'; } return 0; }
1
#2 22 Days Ago
C++ Syntax (Toggle Plain Text)
// strings and c-strings #include <iostream> #include <cstring> #include <string> #include <vector> using namespace std; vector<string> SplitString (string aString) { vector<string> vec; char * cstr, *p; //string str ("Please split this phrase into tokens"); string str = aString; cstr = new char [str.size()+1]; strcpy (cstr, str.c_str()); // cstr now contains a c-string copy of str p=strtok (cstr," "); while (p!=NULL) { vec.push_back(p); p=strtok(NULL," "); } delete[] cstr; return vec; } int main () { std::vector<std::string> vec = SplitString("Please split this phrase into tokens"); for (std::vector<std::string>::size_type a = 0; a < vec.size(); ++a) { cout << vec.at(a) << '\n'; } cin.get(); return 0; }
Last edited by iamthwee; 22 Days Ago at 12:29 pm.
*Voted best profile in the world*
![]() |
Similar Threads
- Splitting a string into tokens (C++)
- C++ String Functions (C++)
- strtok (C)
- Code Snippet: Parsing a String into Tokens Using strcspn 1 (C)
- Unresolved External Symbol Error (C++)
- Read a string from a binary file into a C or C++ string (C++)
- no matching function for call to 'strcmp(std::string&, std::string&)' (C++)
- Code Snippet: Parsing a String into Tokens Using strcspn, Part 3 (C)
- Code Snippet: Parsing a String into Tokens Using strcspn, Part 2 (C)
Other Threads in the C++ Forum
- Previous Thread: glColor problem
- Next Thread: A problem with WinBGIm, incorrect metadata
| Thread Tools | Search this Thread |







