如果条件计算字符串中的 "1" 位数字未执行

if conditional for counting "1" digits in a string not executing

本文关键字:执行 数字 条件 计算 字符串 如果      更新时间:2023-10-16

我必须将二进制字符串的每一位与1进行比较;如果位为1,则计数器增加1。

#include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main(int argc, char const *argv[])
{
    int n, d;
    cin >> n >> d;
    string a1("1");
    int count = 0;
    int sum[1000];
    string a[1000];
    for (int i = 0; i < d; i++) {
        cin >> a[i];
        for (int j = 0; j < n; j++) {
            if (a[j].compare(a1) == 0) {
                count++;
            }
        }
        sum[i] = count;
        cout << sum[i] << endl;
    }
    int kill = 0;
    for (int i = 0; i < d; i++) {
        if (sum[i] == 0) {
            kill++;
        } else if (sum[i] == sum[i + 1]) {
            kill++;
        }
    }
    //cout<<kill<<endl;
    return 0;
}

我已经写了这个逻辑,但是if条件不工作,因为它应该在a[j]为1时执行,但它不是。

我怎样才能正确地做到这一点?

试着用strcmp()代替compare

if (strcmp(a[j], a1) == 0)
{
    count++;
}