use of substr find and []

ok guys this is my code here well my problem is the code wont show up the way its supposed this is what it should do:
//Read a line of 5 words separated by colons and no spaces.
//Extract the 5 words
//Print the 5 words in reverse order, one word per line.
i think my code is alright but when it tried to put them in reverse order it doesn't seem to do it right.

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <cstdlib>
#include <string>
#include <cctype>
using namespace std;
//Progam 1b
//Rohan Shah
//6/2/11
//Read a line of 5 words separated by colons and no spaces.
//Extract the 5 words
//Print the 5 words in reverse order, one word per line.

string words;
string first;
string second;
string third;
string fourth;
string fifth;
string delim;
int pos;

int main ()
{
    
    cout << "enter five words seperate them by colon's and start with a colon\n" 
         << "" ;
    getline(cin, words);
    delim          = words.substr (0, 1);
    pos            = words.find(delim);
    words          = words.substr (1);
    first          = words.substr (0, pos);
    words          = words.substr (pos+1);
    pos            = words.find(delim);
    second         = words.substr (0, pos);
    words          = words.substr (pos+1);
    pos            = words.find(delim);
    third          = words.substr (0, pos);
    words          = words.substr (pos+1);
    pos            = words.find(delim);
    fourth         = words.substr (0, pos );
    words          = words.substr (pos+1);
    pos            = words.find(delim);
    fifth          = words;
    cout << fifth << fourth << third << second << first << endl; ;
        
    system ("pause");
    return 0;
}
Last edited on
What if the exercise asked for 5000 words?
-.- it didnt but i could just use an array and loops to make it easier? btw... you see any problems? please help =x
Last edited on
What did it output and what were you expecting?
ok i typed in
:hi:hello:kemcho:bonjour:kaiseho

i should have got:
kaiseho bonjour kemcho hello hi

but i got..
bonjour:kaiseho kemcho hello hi


according to assignment it isnt supposed to have spaces but i spaced em so easier for u to read
still need help =x
You look for the position of the first delimiter before removing the colon from the beginning of the string, so your first word is always the empty string. Thus, when you get to the end you have two words remaining as your fifth word.
Topic archived. No new replies allowed.