Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why returning string is not printing in C++

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading