splitting a string into an array in C++ without using vector
arrays, c++, string, vector
Solution
It is possible to turn the string into a stream by using the `std::stringstream` class (its constructor takes a string as parameter). Once it's built, you can use the `>>` operator on it (like on regular file based streams), which will extract, or tokenize word from it:
#include <iostream>
#include <sstream>
using namespace std;
int main(){
string line = "test one two three.";
string arr[4];
int i = 0;
stringstream ssin(line);
while (ssin.good() && i < 4){
ssin >> arr[i];
++i;
}
for(i = 0; i < 4; i++){
cout << arr[i] << endl;
}
}
Problem
I am trying to insert a string separated by spaces into an array of strings without using vector in C++. For example: ``` using namespace std; int main() { string line = "test one two three."; string arr[4]; //codes here to put each word in string line into string array arr for(int i = 0; i < 4; i++) { cout << arr[i] << endl; } } ``` I want the output to be: ``` test one two three. ``` I know there are already other questions asking string > array in C++, but I could not find any answer satisfying my conditions: splitting a string into an array WITHOUT using vector.
Related problems
- Parsing a comma-delimited std::string
- Convert String containing several numbers into integers
- How to read numbers from an ASCII file (C++)
- Int tokenizer
- How do I iterate over the words of a string?
- How do I tokenize a string in C++?
- A better way to split a string into an array of strings in C/C++ using whitespace as a delimiter