String reverse, std::string does not allow character assignment?

末鹿安然 提交于 2019-12-13 03:59:30

问题


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?


回答1:


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




回答2:


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());



回答3:


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].




回答4:


Have a try on the STL algorithm of reverse?

include <algorithm>
// ...
std::string str("hello world!");
std::reverse(str.begin(), str.end());



回答5:


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.



来源:https://stackoverflow.com/questions/10681936/string-reverse-stdstring-does-not-allow-character-assignment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!