C++ 逐字母存储字符串并打印它
为什么这个程序不能反向打印“hello”?当我取消对循环中的行的注释时,它会起作用。我想知道为什么字符串值没有被存储。谢谢大家!C++ 逐字母存储字符串并打印它,c++,string,storage,reverse,C++,String,Storage,Reverse,为什么这个程序不能反向打印“hello”?当我取消对循环中的行的注释时,它会起作用。我想知道为什么字符串值没有被存储。谢谢大家! #include<iostream> using namespace std; void reverse(string str) { int length = str.length(); int x = length, i = 0; string newString; while(x &
#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;
}
#包括
使用名称空间std;
无效反向(字符串str){
int length=str.length();
int x=长度,i=0;
字符串新闻字符串;
而(x>=0){
newString[i]=str[x-1];
//coutnewString
的大小为0(使用默认构造函数构造),因此使用newString[i]=
写入字符串末尾会导致未定义的行为。在写入字符串之前,请使用.resize
调整字符串大小(使其足够大)程序存在几个问题
对于初学者,您应该包括标题
否则,每次调用函数时都会创建用作参数的原始字符串的副本
对于大小类型,类std::string
定义自己的名为size\u 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;
}
使用调试器的时间。它可以帮助你很快地找出发生了什么。看看C++中的[]操作符的引用页。它充当一个吸气剂,而不是设定器。恐怕这不是真的。
返回一个引用,允许它执行双重任务。假设字符串
不是常量,也就是说。或者构造一个反向字符串字符串newString(str.rbegin(),str.rend());
您能解释一下使用“const string&str”背后的原因吗请再多一点?谢谢。@aashman使用了对原始字符串的引用,该引用不是原始字符串的副本,而在程序中,每次调用函数时都会创建原始字符串的副本。这是资源消耗。
string 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;
}
#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;
}