逐个字母存储字符串并打印

storing a string letter by letter and printing it

本文关键字:字符串 串并 打印 字符 存储      更新时间:2023-10-16

为什么这个程序不能反向打印出"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调整字符串的大小(使其足够大(

该程序有几个问题。

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

#include <string>

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

最好像这样声明函数

void reverse(const string &str);

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

对于大小类型,类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;
}
相关文章: