I'm taking a string as input for the function, and I'm trying to prepend line numbers to every new line in the string. I'm also returning a string but it keeps giving me this error: stack smashing detected
.
Here's the code:
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;
}
CodePudding user response:
There are several errors in your code,
- you should convert
int
tostring
usingto_string()
- you should iterate
string
using itssize()
...
#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;
}