逐个字母地存储一个字符串并打印它

storing a string letter by letter and printing it

为什么这个程序不会反向打印出"hello"?当我取消注释循环内的行时,它会起作用。我想知道为什么不存储字符串值背后的概念。谢谢!

#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;
}

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

程序有几个问题。

对于初学者,您应该包括 header <string>

#include <string>

因为程序使用了这个 header 的声明。 header <iostream> 不一定包含 header <string>

像这样声明函数会更好

void reverse(const string &str);

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

对于大小类型,class 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;
}

考虑到可以根据 class 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;
}