I am having an issue with my C++ code. I am learning C++. I have written a C++ code for deleting a character from a string. My code is running without an error but not getting a output.
My Code:
#include <iostream>
#include <string>
using namespace std;
string deletion(string s, int position) {
string newS;
int i = 0, j = 0, sLen = s.length();
while(sLen != 0) {
if(i != position) {
newS[j] = s[i];
j++;
}
i++;
sLen--;
}
return newS;
}
int main() {
cout << deletion("abcd", 2) << endl;
return 0;
}
Why I am not getting any output? How to solve this problem?
>Solution :
This string has zero length
string newS;
This code attempts to write a character to a zero length string
newS[j] = s[i];
That is an out of bounds error and therefore your code has undefined behaviour.
Here’s your code rewritten so that it adds characters to the string.
string deletion(string s, int position) {
string newS;
int i = 0, sLen = s.length();
while(sLen != 0) {
if(i != position) {
newS.push_back(s[i]);
}
i++;
sLen--;
}
return newS;
}
I haven’t checked the rest of the logic, but this code is clearly the code you were trying to write. You’re not the first beginner to think that strings grow automatically when you write characters to them, but this is not true.