逐个字母存储字符串并打印
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
调整字符串的大小(使其足够大(
该程序有几个问题。
对于初学者,您应该包括标题<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;
}
相关文章:
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 连接资源文件中的字符串,并将其传递给菜单项字符串 (winapi) c++
- 拆分字符串输入并查找字符是否有效
- 二进制字符数组转换为字符串流并从缓冲区弹出
- 文本文件中的 grep 字符串,并将它们复制到 CMake 中的目录中
- C++最快的字符串小写并查找
- 从文件到字符串读取并传递到功能
- 如何在其中创建2D字符串向量并插入数据
- 输入到字符串流并在单个语句中转换为字符串.可以没有帮助程序类
- 如何查找查看一个字符串是否位于另一个字符串内部并替换它
- std::variant 存储多个字符串类型并区分它们
- 有没有办法将数字作为字符串,并在不使用浮点数或双精度数的情况下将其四舍五入到确切的位数
- 将char添加到字符串中并删除char数组
- 如何将浮子值的字节存储在字符串中并以后检索值
- 如何存储在字符串中并转换为字符数组
- 如何记录QObject::tr的原始字符串,并仍然向GUI显示翻译
- 在班级中使用动态分配的C风格字符串,并带有复制和分配操作员,给出了意外的结果
- 将utf8编码的字符串转换为本地8位编码的字符串,并将无法确定的字符替换为空白
- 将浮点数转换为字符串,并指定精度和十进制数字数?