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