Strings, extracting elements, and recombining to form new string!

I am working on a Lab for my computer science class and these are the topics that I need help with and was hoping someone could help with the coding:

1.) Reading a value into a single string object in the program that contains exactly four words seperated by an *, and then print out that string.

2.) In the same program, extract each word from the original string and store each word in its own string, and print each word out on a separate line.

3.) In the same program, concatenate the words in reverse order to form a new string, and print this out.

It would be greatly appreciated if anyone is willing to help! Thanks

-cgifford
1.) Use std::getline().
2.) Use the .find() and .substr() members of std::string
3.) Use std::string's .append()
I have this code so far! I can't get it to compile correctly! Can anyone help?



#include <string>
#include <iostream>
#include <iomanip>
#include <vector>

int main(int argc, char *argv[])

{
string input; // our input string
vector<string> s_words; // to contain our words
string new_word; // for building the words

cout << "Enter a 4 word sentence: ";
getline (cin, input); // get our input

for (int i = 0; i < input.size(); i++) // for each char in input
{
if (input.at(i) == " ") // if char equal to space
{
if (new_word.size() > 0) // if we have something in new_word
{
s_words.push_back(new_word); // add it to our array
new_word = ""; // clear new_word
}
continue; // go to next iteration of loop
}

new_word.push_back(input.at(i)); // add char to new_word
}

if (s_words.size() != 4) // if we have other than 4 words
{
cout << "Incorrect number of words." << endl; // cout error
return 0; // exit program
}

cout << "Reversed sentence: " << endl;

for (int i = 3; i >= 0; i--) // for each word in reverse
cout << s_words.at(i) << " "; // cout the word

cout << endl; // and finally an endline

system("PAUSE"); // pause system
return 0;
}
Last edited on
Please use [code][/code] tags

You need to add the line using namespace std; after including the headers
if (input.at(i) == " ") // if char equal to space for chars you must use single quotes: ' ' system("PAUSE"); // pause system see http://www.cplusplus.com/forum/articles/7312/ and http://www.cplusplus.com/forum/articles/11153/
Topic archived. No new replies allowed.