display words in a string separatly

Nov 6, 2010 at 8:22am
hi

i am trying to make a simple code. what i want to do is user will enter a string and this code will display each word in that string separatly.

here is what i have done so far but it is not working properly. it does not display any errors but the problem is it does not display words.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>

using namespace std;

int main()
{
string s;
char sep = ' ';

cout << "Enter string: ";
cin >> s;

int len_s = s.length();
//char ch_s[];
//strcpy(ch_s, a.c_str());

for (int a = 0; a <= len_s; a++) {
if(s[a] == sep) {
cout << s << endl;
}
}
return 0;
}

please help
Nov 6, 2010 at 8:52am
Your code prints the string for every white space found. If you have a string with several words and want to print each word in a separate line, you could just print a '\n' instead of every ' '.
1
2
3
for (int a = 0; a <= len_s; a++)
   if(s[a] == sep) cout << '\n';
   else cout << s[a];

Another problem is that cin >> s will only read one word, so there will be no ' 's. use getline.
If you want to store each string separately, you could do this
1
2
3
4
5
vector<string> vec;
string s;
getline(cin, s);
stringstream ss(s);
while(ss >> s) vec.push_back(s);
or something like that..
Topic archived. No new replies allowed.