Home > Mobile >  Why do I have a line break?
Why do I have a line break?

Time:03-27

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

CodePudding user response:

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.

  • Related