output is not as expected it should print 12 not 102

Viewed 50

output should be 12 not 102 why is it not deleting all the zeros

#include<bits/stdc++.h>

using namespace std;

int main()
{
    string s="10002";
    for(int i=0;i<s.size();i++)
    if(s[i]=='0')
    s.erase(s.begin()+i);
    cout<<s;
}
3 Answers

It’s skipping a value because the loop counter gets incremented even when you erase characters. You need to decrement i when you erase a 0

if (s[i] == 0) {
    s.erase(s.begin() + i);
    i--;
}

Let's dry run your code.

  1. i = 0, s[0] != '0' (does nothing)
  2. i = 1, s[1] = '0' (it erases the '0' at second index, now the string is "1002")
  3. i = 2, s[2] = '0' (it erases the '0' at third index, now the string is "102")
  4. i = 3, but the size of string is also 3, so the loop breaks because of the condition i<s.size().

Hence 102 is printed.

As @DanMulin mentioned, it's skipping value because when you deleted a character, the std::string size is decreased but i keeps getting increased. To solve it, add a i--.

#include <iostream>
#include <string>

int main()
{
    std::string s="10002";
    for(int i=0; i<s.size(); i++)
    {
        if(s[i]=='0')
        {
            s.erase(s.begin()+i); i--;
        }
    }
    std::cout << s;
}

Or to avoid this all together, you can use a while loop instead (which I recommended more when manipulating std::strings):

#include <iostream>
#include <string>

int main()
{
    std::string s="10002";
    int inc = 0;
    while(inc < s.length())
    {
        while(s[inc] == '0') { s.erase(s.begin()+inc); }
        inc++;
    }
    std::cout << s;
}

Also, see

Related