首页 > 解决方案 > 此代码显示错误,弹出窗口“调试断言失败”

问题描述

所以这段代码在运行时弹出一个错误窗口,说调试断言失败并且字符串下标超出范围?

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








标签: c++string

解决方案


std::string不同于普通的 char 数组。它们存储额外的东西,例如字符串的长度,有时实际的字符串是单独存储的。因此,sizeof(word)不会为您提供正确的字符串长度。

只需使用word.size()来获取字符串的长度。

此外,您的字符串converted不包含任何字符,因此converted[i]访问无效索引也是如此。解决此问题的一种方法是将新字符添加到循环中字符串的末尾,方法是converted += word[size - i - 1].


推荐阅读