0

Lets say we need to delete the character 'M' with C++.

Here I get an execption at line string[j] = string[j + 1];

When the error is generated the value of I and j both is 4.

Also let me know if I have passed the value of string properly, I am not sure about how the string is terminated.

This question seems to be answered before but it is not! Since, the code with others is different!!

#include<iostream>
#include<conio.h>
#include<string>

using namespace std;

void func(char string[])
{
    for (int i = 0; i < strlen(string); i++)
    {
        if (string[i] == 'M')
        {
            for (int j = i; j < strlen(string); j++)
            {
                string[j] = string[j + 1];
                            (this is where an exception being is generated)
            }
        }
    }
    cout << "string finally - " << string;
}

int main()
{
    func("GoodMorning\0");

    int buffer;
    cin >> buffer;

    return 0;
}

1 Answers1

3

You're attempting to modify the contents of a string literal. You can't do that.

Drop the C-string antiquities and use std::string; having included <string> you're almost there.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055