Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- using namespace std;
- // Take a sequence of words and
- // display them in reverse order.
- int main()
- {
- string sequence_of_words; // User input.
- cout << "Enter any number of words:" << endl;
- getline(cin, sequence_of_words); // Get the words.
- int space_location = 0; // Location of a space.
- int start_position = 0; // Begin a new word.
- int length = 0; // Length of the word.
- string word; // A word.
- vector<string> separate_words;
- cout << "Here are your words in reverse order:" << endl;
- if (!sequence_of_words.empty()) // If the user entered words,
- {
- // While there is a space in the sentence,
- while ( (space_location = sequence_of_words.find(" ", start_position)) != string::npos)
- {
- // Get the length of the word.
- length = space_location - start_position;
- // Get the word.
- word = sequence_of_words.substr(start_position, length);
- // Add the word to the vector.
- separate_words.push_back(word);
- // This is the start of the next word.
- start_position = space_location + 1;
- }
- // If there are no more spaces,
- // Get the length of the last word.
- length = sequence_of_words.size() - start_position;
- // Get the last word.
- word = sequence_of_words.substr(start_position, length);
- // Add the word to the vector.
- separate_words.push_back(word);
- // Find out how many words there are.
- size_t list_size = separate_words.size();
- // Start at the end of the list.
- for (int x = 1; x <= list_size; ++x)
- {
- // Display the word.
- cout << separate_words[list_size - x] << " ";
- }
- // Go to the next line.
- cout << endl;
- }
- else // If the user did not enter anything,
- {
- cout << "No words were entered." << endl;
- }
- // End the program.
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement