Need help with this simple code

Here is my code, please fix it if you can. The output doesn't do anything. It just displays what was entered.

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
#include <iostream>
#include <string>
#include <vector>

using namespace std;

void main ()
{

string str;

vector<string> vWords;
cout << "Please enter a phrase" << endl;
getline(cin, str);
while(1)
{
    string temp;
    unsigned int pos = str.find_first_of(' ');
    if(-1 == pos)
        break;
    temp = str.substr(0, pos);
    vWords.push_back(temp);
    str.erase(0, pos + 1);
}
cout << "Backwards: " << str << endl;
}


This program should reverse a phrase, but only the order of the words should be reversed. The words themselves must remain as words. Also the number of spaces should remain the same.


Thanks to those who help!!!
Where you want print vWords? #25 is going to print nothing.

By the way, you don't need vector if it's not madatory part of your practicing.

Just use another string to add substring back like reverStr = temp + reverStr, then you can get what your want.


b2ee
closed account (zb0S216C)
In your code, you only print the word given by the user. What you need to do is create a for loop, from the last element of vWords, print each element. This, in theory, should print the given words in reverse order.
Could you please code a for loop for me? It would be much appreciated!!
You got all answers in thread that you took code from
http://www.cplusplus.com/forum/general/41984/

Just add this:
1
2
3
4
5
6
std::vector<std::string>::reverse_iterator rb(vWords.begin());
std::vector<std::string>::reverse_iterator re(vWords.end());
while(re < rb)
{
	std::cout << *re++ << " ";
}

instead your line #25. But note that it isn't complete since it never inserts last word into vector.

Here is fix to insert last word:
1
2
3
4
5
6
7
8
9
10
11
while(1)
{
   ...
   if(-1 == pos)
   {
	temp = str.substr(0, pos);
	vWords.push_back(temp);
	break;
   }
   ...
}
Last edited on
Topic archived. No new replies allowed.