Trying to put pieces of a string in a vector

Hey Everyone,

I'm trying to explode a string and put each word in a vector. I don't know how to use stringstream yet, and I'm trying to get practice at using some of the member functions of string. I can get the first word in the right position, but then I can't figure out why I get the 2nd word plus the first 3 chars of the 3rd word in the 2nd position. Any help is appreciated.

thanks community!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main(){
	string s;
	vector<string> word;
	cout << "Enter a string: \n";
	getline(cin, s);
	size_t found;
	size_t found1;
	found = s.find_first_not_of(" ");
	found1 = s.find_first_of(" ");
	while(found1 != string::npos){
		word.push_back(s.substr(found, found1));
		found = found1 + 1;
		found1 = s.find_first_of(" ", found1 + 1);
	}

	for (unsigned int i = 0; i < word.size(); ++i){
		cout << word[i];
		cout << endl;
	}

	return 0;
}


Last edited on
The second argument to substr is the length of the substring.
wow, thanks for pointing out that mistake. I thought the two arguments were a range, I'll try and correct it! Wish there was a member function that allowed one to specify a range.
Here is my new code that works for everything but the last word of the string, because there is no space after the last word in the string. I know I could do it by searching for a period the same way I search for a space for the last word, and that would always work as long as there was a period, but I thought I'd ask if anyone else has other suggestions for this situation. Am I going about this the right way? thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main(){
	string s;
	vector<string> word;
	cout << "Enter a string: \n";
	getline(cin, s);
	size_t found;
	size_t found1;
	found = s.find_first_not_of(" ");
	found1 = s.find_first_of(" ");
	while(found1 != string::npos){
		word.push_back(s.substr(found,found1-found));
		found = found1 + 1;
		found1 = s.find_first_of(" ", found1 + 1);
		if()
	}

	for (unsigned int i = 0; i < word.size(); ++i){
		cout << word[i];
		cout << endl;
	}

	return 0;
}
@line 22, found1 euqals npos, so just push_back() from found to found1 (or whatever math is needed to work it).
Thanks LowestOne, I just implemented your suggestion and it works like a charm.

I've read about string::npos but I don't have the greatest understanding of it. I guess as long as I know how to use it, thats the most important thing. So far I just know it can be used as a parameter to mean the end of a string. If someone has a better understanding and cares to explain, I know I will benefit from it.

Thanks again cpp community, you've really helped me out!
Topic archived. No new replies allowed.