I'm trying to write a code to reverse the a sentence. For example,
Input - "I like to get answer from stackoverflow"
Output - "Stackoverflow from answer to get like I"
I wrote the following code but somehow when I add a string to the vector it is not working. But the program compiles fine. Can someone help me out. Below is the code
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<string> s;
string input;
cin>>input;
string temp="";
for(int i=0;input[i]!='\0';i )
{
if(input[i]==' ')
{
s.push_back(temp);
temp="";
}
else
{
temp=temp input[i];
cout<<temp<<endl;
}
}
for(int i=0;i<s.size();i )
{
cout<<s[i]<<" ";
}
}
CodePudding user response:
You want to read an entire line into a string. cin >> input
will read only the first word of the line. You can use cin.getline()
method to read an entire line.
CodePudding user response:
first we read a string using cin, we will exit from the stream using the "exit" keyword.
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<string> s;
string input;
for (int i = 0; i < 10; i ) {
cin >> input;
if (input == "exit") // breaking from the loop
break;
s.push_back(input); //adding word at the end of vector s
}
for (int i = s.size()-1; i >= 0; --i) // starting loop from the last index(s.size()-1)
cout << s[i] << ' ';
}
Input :
I like to get answer from StackOverflow
exit
Output :
stackoverflow from answer get to like I
CodePudding user response:
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<string> sentence;
string input;
getline(cin, input);
stringstream s(input);
while(s >> input)
{
sentence.push_back(input);
}
std::reverse(sentence.begin(), sentence.end());
for(const auto& word : sentence)
std::cout << word << " ";
return 0;
}