string words into aray

say i have a string called "org_string"
org_string = "REFRACTIVE LIGHT";

i also have a string array called keys[6];
keys has 6 elements(obviously) and right now all of those elements are equal to the null terminator "\0"

can somebody write me a function that splits org_string into the two words separated by spaces within it and place the words in separate elements of keys[];
i.e.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
std::string org_string = "REFRACTIVE LIGHT";
std::string keys[6];
keys[0] = '\0';
keys[1] = '\0';
keys[2] = '\0';
keys[3] = '\0';
keys[4] = '\0';
keys[5] = '\0';

//code that gives me this output

keys[0] = "REFRACTIVE";
keys[1] = "LIGHT";
keys[2] = '\0';
keys[3] = '\0';
keys[4] = '\0';
keys[5] = '\0';


please help me if you can.. i've been struggling with this all day.
God, please, intead of this poor formated array, use a vector.
This might not be the prettiest, but it gets the job done.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;

int main() {
	string org_string = "REFRACTIVE LIGHT", fill_val;
	std::vector<string> keys;
	
	auto itersplit = [](const string &myword, string &token) ->bool {
		static istringstream word(myword);
		return (bool)(word >> token);
	};
	
	while (itersplit(org_string, fill_val)) {
		keys.emplace_back(fill_val);
	}
	
	for (auto key: keys)
		cout << key << endl;
	return 0;
}


http://coliru.stacked-crooked.com/a/c0359988f869103a


There are many ways to split strings in c++, this question asking the same thing on SO, has so many replies so you really have no excuse for not having a way to split strings in c++. Even the string library has a split method.
http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c

my custom method, also included in the above thread:
http://stackoverflow.com/a/20807773/2089675
Last edited on
@OP: By default, C++ strings are empty. Lines 14-17 assign one character to the strings, so the strings are not empty but instead contain the null character, giving them a length of 1 and not 0.
You can use getline. Google "c++ getline delimiter".
Topic archived. No new replies allowed.