0

I have written a code in c++ to count zeros. The input have to take as string. The input will be a digit with 1 and 0.

Example:

Input: 1000000001 Output: 8

The answer should be 8 but my code is showing 0. Where is the problem in the code.

Code:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string players;
    cin >> players;
    int count = 0;
    for (int j = 0; j < players.length(); j++)
    {
        if (players[j] == 0)
        {
            count++;
        }
    }
    cout << count;

    return 0;
}

Please help me to find and solve it. Thank you.

  • 2
    Try using `players[j]=='0'`, as your check will check for the null terminator – JCWasmx86 Jul 18 '20 at 14:43
  • 2
    [Why should I not #include ?](https://stackoverflow.com/q/31816095/5910058) / [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/q/1452721/5910058) – Jesper Juhl Jul 18 '20 at 14:48

3 Answers3

3

you need to compare with char not int:

if (players[j] == '0')
Oblivion
  • 7,176
  • 2
  • 14
  • 33
3

if condition for players[j] == 0 is wrong, your input is string type while you are trying to compare with the integer type 0. The correct if check is players[j] == '0'. Using bits/stdc++.h and using namespace std; is a big no in C++.

#include <iostream>
#include <string>

int main()
{
    std:: string players;
    std:: cin >> players;
    int count = 0;
    for(const char &player : players)
    {
        if (player == '0')
        {
            count += 1;
        }
    }
    std:: cout << count;

    return 0;
}
Arun Suryan
  • 1,615
  • 1
  • 9
  • 27
1

the condition is wrong. write code like

players[j] == "0"

your condition means that

player[j] == NULL
Kungfu Frog
  • 81
  • 1
  • 8