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 do I have a line break?

there is a problem with the code. Displays an error "std::out_of_range at memory location". during debugging.
The task of the code is to find all the letters "A" in the text and delete them.
**С++ code:
**

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string a;
    getline(cin, a);
    int n = 0;
    do {
        n = a.find('a',1);
        cout << n;
        a.erase(n, 0);
        cout << a;
    } while (n != -1);
    cout << a;
}

I tried to change int to double, but the program does not work correctly. However, the error disappears

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 :

There are two problems with this do-while loop

do {
    n = a.find('a',1);
    cout << n;
    a.erase(n, 0);
    cout << a;
} while (n != -1);

The first one is that you are starting to search the letter ‘a’ starting from the position 1 instead of the position 0.

The second one is that if the letter ‘a’ is not found then n is equal to std::string::npos and you are using this value in the call of erase. You need to check that n is not equal to std::string::npos before calling the member function erase.

And the call of erase in any case is incorrect.

Instead of the do-while loop it is better to use the for loop. For example

for ( std::string::size_type n; ( n = a.find( 'a' ) ) != std::string::npos; )
{ 
    std::cout << n;
    a.erase(n, 1 );
    std::cout << a << '\n';
}

Also you should declare the variable n as having the type std::string::size_type.

And as @Ted Lyngmo wrote in a comment if your compiler supports C++ 20 then you can use standard C++ function erase defined for standard containers like

std::erase( a, 'a' );

to remove all occurrences of the letter 'a' in the string.

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