Akram Mohammed
Akram Mohammed

Reputation: 151

Error in implementing String comparison in C++

My string s contains 0's and 1's. Why are the values of Ascore and Bscore zero, and not incrementing given the conditions below?

int main()
{
        long long int n;
        string s;
        cin>>n;   // 3
        cin.ignore();
        long long int siz = 2*n, Ascore = 0, Bscore = 0;
        cin>>s; // 101011
        for(int i = 0; i < siz; i++ )
        {

            if((i%2 == 0) && (s[i] == 1))
                Ascore++;
            if((i%2 == 1) && (s[i] == 1))
                Bscore++;
            if(abs(Ascore-Bscore) == 2)
                cout<<i+1<<"\n";
            if((i % 2 == siz-1) && (Ascore == Bscore))
                cout<<i+1<<"\n";


        }

}

Upvotes: 0

Views: 59

Answers (2)

Hunali
Hunali

Reputation: 277

You are using a integer 1 instead of character '1'

  for(int i = 0; i < siz; i++ )
        {

            if((i%2 == 0) && (s[i] == '1'))
                Ascore++;
            if((i%2 == 1) && (s[i] == '1'))
                Bscore++;
            if(abs(Ascore-Bscore) == 2)
                cout<<i+1<<"\n";
            if((i % 2 == siz-1) && (Ascore == Bscore))
                cout<<i+1<<"\n";


        }

Upvotes: 1

cigien
cigien

Reputation: 60208

A string is composed of chars, so you need to compare against char literals, not ints. e.g.

s[i] == '1'

instead of

s[i] == 1

Upvotes: 1

Related Questions