在字符串中加入行号时出错"stack smashing detected"



我将一个字符串作为函数的输入,并尝试在字符串中的每一行前面加上行号。我也返回了一个字符串,但它一直给我这个错误:stack smashing detected

这是代码:

string prepend(string code) {
string arr;
int i = 0;
int j = 0;
int count = 100;    
while (code[i] != '') {
if (j == 0) {
arr[j] = count;
arr[j + 3] = ' ';
j = j + 4;
}
if (code[i] == 'n') {
arr[j + 1] = count;
arr[j + 3] = ' ';
j = j + 4;
}
arr[j] = code[i];
i++;
j++;
count++;
}

return arr;
}

您的代码中有几个错误,

  1. 您应该使用to_string()int转换为string
  2. 应该使用size()迭代string
#include <iostream>
#include <string>
using namespace std;
string prepend(string code) {
string arr;
int count = 1;
arr += to_string(count++) + " ";
for (size_t i = 0; i < code.size(); ++i) {
arr += code[i];
if (code[i] == 'n') {
arr += to_string(count++) + " ";
}
}
return arr;
}
int main(int argc, char **argv) {
string code = "anbcnd ef gnn";
cout << prepend(code);
return 0;
}

最新更新