In: Computer Science
C++
// Program Description: This program accepts three 3-letter words and prints out the reverse of each word
A main(. . . ) function and the use of std::cin and std::cout to read in data and write out data
as described below.
Variables to hold the data read in using std::cin and a return statement.
#include <iostream >
int main(int argc, char *argv[]) {
.... your code goes here
}//main
Example usage:
>A01.exe Enter three 3-letter space separated words, then press enter to display the reverse: cat eye fix tac eye xif Enter any key to exit:
Code:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int reverse_words(string str)
{
stack <char> stck;
// Traverse given string and push all characters to
stack until we see a space.
for(int i=0;i<str.length();i++)
{
if(str[i]!=' ')
{
stck.push(str[i]);
}
else
{
while(stck.empty()==false)
{
cout << stck.top();
stck.pop();
}
cout << "
";
}
}
//There is no space after last word
while(stck.empty()==false)
{
cout << stck.top();
stck.pop();
}
return 0;
}
//main
int main()
{
//Taking string as input
cout << "Enter three 3-letter space separated
words, then press enter to display the reverse:\n";
std::string str;
std::getline(std::cin,str);
reverse_words(str);
return 0;
}
Screenshot of the program:
Output: