我將一個字符串作為函數的輸入,並且我試圖在字符串中的每個新行之前添加行號。我也返回一個字符串,但它不斷給我這個錯誤:stack smashing detected
。
這是代碼:
string prepend(string code) {
string arr;
int i = 0;
int j = 0;
int count = 100;
while (code[i] != '\0') {
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;
}
您的代碼中有幾個錯誤,
int
為string
使用to_string()
string
使用它的size()
......#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 = "a\nbc\nd ef g\n\n";
cout << prepend(code);
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句