Advertisement
janac

Display words in reverse order

Nov 19th, 2021
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1.  
  2.  
  3. #include <iostream>
  4. #include <string>
  5. #include <vector>
  6. using namespace std;
  7.  
  8. // Take a sequence of words and
  9. // display them in reverse order.
  10. int main()
  11. {
  12.     string sequence_of_words; // User input.
  13.  
  14.     cout << "Enter any number of words:" << endl;
  15.     getline(cin, sequence_of_words); // Get the words.
  16.  
  17.     int space_location = 0; // Location of a space.
  18.     int start_position = 0; // Begin a new word.
  19.     int length = 0; // Length of the word.
  20.     string word; // A word.
  21.     vector<string> separate_words;
  22.  
  23.     cout << "Here are your words in reverse order:" << endl;
  24.     if (!sequence_of_words.empty()) // If the user entered words,
  25.     {
  26.         // While there is a space in the sentence,
  27.         while ( (space_location = sequence_of_words.find(" ", start_position)) != string::npos)
  28.         {
  29.             // Get the length of the word.
  30.             length = space_location - start_position;
  31.  
  32.             // Get the word.
  33.             word = sequence_of_words.substr(start_position, length);
  34.  
  35.             // Add the word to the vector.
  36.             separate_words.push_back(word);
  37.  
  38.             // This is the start of the next word.
  39.             start_position = space_location + 1;
  40.         }
  41.  
  42.         // If there are no more spaces,
  43.         // Get the length of the last word.
  44.         length = sequence_of_words.size() - start_position;
  45.  
  46.         // Get the last word.
  47.         word = sequence_of_words.substr(start_position, length);
  48.  
  49.         // Add the word to the vector.
  50.         separate_words.push_back(word);
  51.  
  52.         // Find out how many words there are.
  53.         size_t list_size = separate_words.size();
  54.  
  55.         // Start at the end of the list.
  56.         for (int x = 1; x <= list_size; ++x)
  57.         {
  58.             // Display the word.
  59.             cout << separate_words[list_size - x] << " ";
  60.         }
  61.        
  62.         // Go to the next line.
  63.         cout << endl;
  64.     }
  65.     else // If the user did not enter anything,
  66.     {
  67.         cout << "No words were entered." << endl;
  68.     }
  69.  
  70.     // End the program.
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement