c++ - 此代码显示错误,弹出窗口“调试断言失败”
问题描述
所以这段代码在运行时弹出一个错误窗口,说调试断言失败并且字符串下标超出范围?
//aim of this code is to convert a string to its reversed ::: sample input yeah ::: output haey
#include<iostream>
#include <string>
using namespace std;
int main() {
string word;
string converted;
cin >> word;
int size = word.size();
for (int i = 0; i < size; i++) {
converted[i] = word[size - i-1];
}
cout << converted;
return 0;
}
解决方案
std::string
不同于普通的 char 数组。它们存储额外的东西,例如字符串的长度,有时实际的字符串是单独存储的。因此,sizeof(word)
不会为您提供正确的字符串长度。
只需使用word.size()
来获取字符串的长度。
此外,您的字符串converted
不包含任何字符,因此converted[i]
访问无效索引也是如此。解决此问题的一种方法是将新字符添加到循环中字符串的末尾,方法是converted += word[size - i - 1]
.
推荐阅读
- r - R中多个LASSO回归的“lambda.min”值不变
- aspnetboilerplate - AspNet 样板:Hangfire 队列
- typescript - 为什么在这种特定情况下使用映射类型会解析为联合?
- java - Eclipse 无法识别 Confluent jar
- .net - 在 Zebra ZXP 系列 3 打印机中打印条形码
- html - 如何设置下载链接的文件名?
- azure - Azure DevOps:无法再在项目设置中看到扩展
- linux - 为什么非 pic 代码不能使用运行时修复完全成为 ASLR?
- android - Android TextInputLayout 在 RecyclingView 内缓慢渲染
- c++ - 为什么我不能使用 std::next_permutation 生成所有排列?