逐字存储字符串并打印

时间:2017-07-11 00:15:27

标签: c++ string storage reverse

为什么不打印这个节目"你好"相反?当我取消注释循环内的行时,它可以工作。我想知道为什么字符串值没有被存储的概念。谢谢!

#include<iostream>

using namespace std;

void reverse(string str) {
        int length = str.length();
        int x = length, i = 0;
        string newString;

        while(x >= 0) {
                newString[i] = str[x-1];
                //cout << newString[i];
                x--;
                i++;
        }

        cout << newString;
}

int main() {
        reverse("hello");

return 0;
}

2 个答案:

答案 0 :(得分:5)

newString的大小为0(使用默认构造函数构造),因此使用newString[i] =写入它的末尾会导致未定义的行为。在写入之前使用.resize调整字符串的大小(使其足够大)

答案 1 :(得分:2)

该计划存在一些问题。

对于初学者,您应该包含标题<string>

#include <string>

因为程序使用此标头中的声明。标题<iostream>不一定包含标题<string>

声明像

这样的函数要好得多
void reverse(const string &str);

否则每次调用函数时都会创建用作参数的原始字符串的副本。

对于size类型,类std::string定义了自己的名为size_type的无符号整数类型。最好使用它或类型说明符auto而不是类型int

此声明之后

string newString;

newString为空。所以你可能不会应用下标运算符。您应该调整字符串的大小,或者为字符串中新添加的元素保留足够的内存。

考虑到这一点,可以通过以下方式定义功能。

#include <iostream>
#include <string>

using namespace std;

void reverse( const string &str) {
        auto length = str.length();
        string newString;
        newString.reserve( length );

        for ( auto i = length; i-- != 0;  ) newString += str[i];

        cout << newString << endl;
}

int main() {
        reverse("hello");

        return 0;
}

考虑到可以根据类std::string本身的功能更简单地定义函数。例如

#include <iostream>
#include <string>

using namespace std;

void reverse( const string &str) {
        string newString( str.rbegin(), str.rend() );

        cout << newString << endl;
}

int main() {
        reverse("hello");

        return 0;
}