This is my code to reverse a string using std::string
. But it does not work..
#include <string>
#include <iostream>
using namespace std;
main()
{
string input;
int i, j;
cout << "Enter a string: ";
getline(cin,input);
string output;
for(i = 0, j = input.length() - 1; i < input.length(); i++, j--)
output[i]=input[j];
cout << "Reversed string = " << output;
cin.get();
}
But if we replace string output as char output[100];
it works. So std::string
does not allow character assignments?
You have to resize output:
output.resize(input.length());
or initially set length:
string output(input.length(), ' ');
#include <string>
#include <iostream>
using namespace std;
main(){
string input;
int i,j;
cout << "Enter a string: ";
getline(cin,input);
string output(input.length(), ' '); // initially set sufficient length
for(i=0,j=input.length()-1;i<input.length();i++,j--)
output[i]=input[j];
cout << "Reversed string = " << output;
cin.get();
}
See also:
std::string
std::string
allows character assignments, but not beyond the end of the string. Since std::string output;
creates an empty string, output[0]
is beyond the end of the string.
Presumably this is a learning exercise, but you may as well also be aware of some tools that will do it for you:
#include <string>
#include <iostream>
#include <algorithm>
int main() {
std::string input;
std::getline(cin,input);
std::cout << "input: " << input << '\n';
std::reverse(input.begin(), input.end());
std::cout << "reversed: " << input << '\n';
}
or:
#include <iterator>
...
std::string output;
std::reverse_copy(input.begin(), input.end(), std::back_inserter(output));
std::cout << "reversed: " << output << '\n';
or:
std::string output;
std::copy(input.rbegin(), input.rend(), std::back_inserter(output));
or:
std::string output(input.rbegin(), input.rend());
Because output
is an empty string output[i]
will access invalid memory location. Simply append the character to the output
string using output += input[j]
.
Have a try on the STL algorithm of reverse?
include <algorithm>
// ...
std::string str("hello world!");
std::reverse(str.begin(), str.end());
After constructing string output;
it have 0 length. You need to resize it to input.length()
.
string output;
output.resize(input.length());
Resizing is faster then appending char by char, but you have to know the size first.