Whats wrong in this code? The string is not reversed even when I wrote s.reverse(). It is showing the same string without reversing? Can someone help me with this?
#include<iostream>
using namespace std;
int main(){
cout << "Hello world" << endl;;
string s;
cin >> s;
s.reverse();
cout << s;
}
CodePudding user response:
When you examine the reference document, you will see that the reverse method has the following prototype:
void reverse (BidirectionalIterator first, BidirectionalIterator last);
This method reverses the order of the elements in the range [first,last]
.
Update the line where std::reverse()
is called as follows:
#include <algorithm>
std::reverse(s.begin(), s.end());
CodePudding user response:
std::string
doesn't have a reverse()
method, so calling s.reverse()
shouldn't even compile.
You need to use the std::reverse()
algorithm instead:
#include <iostream>
#include <string>
#include <algorithm>
int main(){
std::cout << "Hello world" << std::endl;
std::string s;
std::cin >> s;
std::reverse(s.begin(), s.end());
std::cout << s;
}
CodePudding user response:
You have used the reserve() function which is different from reverse. To reverse your string modify your code as shown below:
#include <bits/stdc .h>
using namespace std;
int main(){
cout << "Hello world" << endl;
string s;
cin >> s;
reverse(s.begin(), s.end());
cout << s;
}