0

这是我使用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();
}

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

4

5 回答 5

10

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());
于 2012-05-21T09:05:27.970 回答
5

您必须调整输出大小:

output.resize(input.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();
}

参见: std::string

于 2012-05-21T08:43:32.577 回答
4

因为output是空字符串output[i]会访问无效的内存位置。只需使用 . 将字符附加到output字符串即可output += input[j]

于 2012-05-21T08:41:18.453 回答
3

试试反向的STL算法?

include <algorithm>
// ...
std::string str("hello world!");
std::reverse(str.begin(), str.end());
于 2012-05-21T09:11:07.897 回答
1

构建后string output;它的长度为0。您需要将其调整为input.length().

string output;
output.resize(input.length());

调整大小比逐个字符附加要快,但您必须先知道大小。

于 2012-05-21T08:43:26.580 回答