194k views
3 votes
Reverse Word Order: Write a program that reverses the order of the words in a given sentence. This program requires reversing the order of the words wherein the first and last words are swapped, followed by swapping the second word with the second to last word, followed by swapping the third word and the third to last words, and so on. Your program will ask the user for an input string and print out the resultant string where the order of the words is reversed. Please see the hints section for more details on an example algorithm. Assume a maximum C-string size of 1000 characters. Make sure your code works for any input number, not just the test cases. Your code will be tested on other test cases not listed here. Do Not Use Predefined Functions from the cstring Library. Please properly comment your code before submission.For this part of the assignment, name your source file as Reverse Word Order_WSUID.cpp. For example, if your user ID is A999B999 name your file as Reverse Word Order_A999B999.cpp. Sample Test Cases: Test Case 1: Input: London bridge has been abducted Output: abducted been has bridge London Test Case 2: Input: Hello World Output: World Hello Test Case 3: Input: Hello World, how are you? Output: you? Are how World, HelloTest Case 4: Input: I like toast Output: toast like l

1 Answer

0 votes

Answer:

The program in C++ is as follows:

#include <bits/stdc++.h>

using namespace std;

int main(){

string sentence,word="";

getline (cin, sentence);

vector<string> for_reverse;

for (int i = 0; i < sentence.length(); i++){

if (sentence[i] == ' ') {

for_reverse.push_back(word);

word = ""; }

else{ word += sentence[i];} }

for_reverse.push_back(word);

sentence="";

for (int i = for_reverse.size() - 1; i > 0; i--){

sentence+=for_reverse[i]+" ";}

sentence+=for_reverse[0];

cout<<sentence<<endl;

return 0;

}

Step-by-step explanation:

This declares sentence and word as strings; word is then initialized to an empty string

string sentence,word="";

This gets input for sentence

getline (cin, sentence);

This creates a string vector to reverse the input sentence

vector<string> for_reverse;

This iterates through the sentence

for (int i = 0; i < sentence.length(); i++){

This pushes each word of the sentence to the vector when space is encountered

if (sentence[i] == ' ') {

for_reverse.push_back(word);

Initialize word to empty string

word = ""; }

If the encountered character is not a blank space, the character is added to the current word

else{ word += sentence[i];} }

This pushes the last word to the vector

for_reverse.push_back(word);

This initializes sentence to an empty string

sentence="";

This iterates through the vector

for (int i = for_reverse.size() - 1; i > 0; i--){

This generates the reversed sentence

sentence+=for_reverse[i]+" ";}

This adds the first word to the end of the sentence

sentence+=for_reverse[0];

Print the sentence

cout<<sentence<<endl;

User Marventus
by
5.8k points