LET1S3N
LET1S3N

Reputation: 28

comparing elements on a given string

my goal is to print on the console the word "YES" if there are at least seven equal characters together. Here is my code what i dont understand is why it runs for this input: "1000000001" but it doesn't for "00000001" or "100000001" . help please.

#include <iostream>
#include <cstdio>

using namespace std;

string cad1;
int cont=1;

int main(){
    cin >> cad1;

    for(int i=1;i<cad1.length();i++){

            if(cad1[i] == cad1[i-1]){
                       cont++;           
            }else{
                  cont=1;
            }

    }

    if(cont >= 7){
          cout << "YES" << endl;          
    }else{

          cout << "NO" << endl;
    }

    cin.get();    

}

Upvotes: 1

Views: 77

Answers (3)

Ansh David
Ansh David

Reputation: 672

Although Its already answered, here is another way using strtok (COMES IN HANDY WHEN DEALING WITH STRINGS MANIPULATIONS)

#include <stdio.h>
#include <string.h>

int main ()
{
    char str[] ="1000000001";
    char * pch;
    int count =0;

    for(pch = strtok(str, "1"); pch!=NULL; pch = strtok( NULL, "1"))
    {
            //printf("\n%s\n",pch);
            count+=strlen(pch);
    }
    printf("\ntimes -%d", count);

return 0;
}

Upvotes: 0

atrix
atrix

Reputation: 21

Your code is not working for me with "1000000001". If you remove last 1 it works. Put break, when counter reaches 7, and it will work.

Upvotes: 1

BWG
BWG

Reputation: 2278

You are testing it wrong, you compare the value to the previous one. So this string:

1    0    0    0    0    0    0    0    1

Evaluates to this: (F = false, T = true)

1    0    0    0    0    0    0    0    1
  F    T    T    T     T    T    T    F

Each T or F is the result of testing the two above characters.

Count the T's, there are 6. You need to rethink your test.

Some code like this might help:

char current = 0;
int length = 1;
bool foundSeven = false;
for(int i = 0; i < cad1.length(); i++) {
    if(current == cad1[i]) {
        length++;
    } else {
        length = 1;
    }
    current = cad1[i];
    if(length == 7) {
        foundSeven = true;
        break;
    }
}

Upvotes: 3

Related Questions