字符串反向,std :: string不允许字符赋值?

Xeg*_*ara 0 c++ stdstring

这是我使用反转字符串的代码std::string.但它不起作用..

#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();
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我们替换字符串输出,char output[100];它会工作.所以std::string不允许角色分配?

Ste*_*sop 10

std::string允许字符分配,但不能超出字符串的结尾.由于std::string output;创建一个空字符串,output[0]超出了字符串的结尾.

大概这是一个学习练习,但您也可以了解一些可以为您做的工具:

#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';
}
Run Code Online (Sandbox Code Playgroud)

要么:

#include <iterator>
...

    std::string output;
    std::reverse_copy(input.begin(), input.end(), std::back_inserter(output));
    std::cout << "reversed: " << output << '\n';
Run Code Online (Sandbox Code Playgroud)

要么:

    std::string output;
    std::copy(input.rbegin(), input.rend(), std::back_inserter(output));
Run Code Online (Sandbox Code Playgroud)

要么:

    std::string output(input.rbegin(), input.rend());
Run Code Online (Sandbox Code Playgroud)


Rub*_*ben 5

你必须调整输出大小:

output.resize(input.length());
Run Code Online (Sandbox Code Playgroud)

或者最初设定长度:

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();
}
Run Code Online (Sandbox Code Playgroud)

另请参见: std :: string