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

My C++ code is not removing all the zeroes

I have written a simple C++ code which takes an Integer as input and converts it into string, and when iterating through it if it encounters any ‘0’ it erases it.

The program successfully removes multiple zeroes only when they are not in consecutively
Can anyone help me understand why it fails when the zeroes are continuously present.

#include <iostream>
#include <string>

using namespace std;
 
int main() {
    int N; cin >> N;

    string str = to_string(N);
    auto it = str.begin();

    for (it; it < str.end(); ++it)
    {
        if (*it == '0')
        {
            str.erase(it);
        }
    }

    cout << str << endl; 
} 
Input = 1509  --> output 159 
Input = 10509 --> output 159 
Input = 15009 --> output 1509
Input = 105009--> output 1509  

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 :

When manipulating the string while looping over it, you have to take care not to loose your position in it. In other word, when removing an element, without correcting your iterator, you’ll skip on character each time.

Sidenote: Better use a STL function for this (as also pointed to in the comments. Also problems like this are glowing examples of why to use std-functions).

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