-3

I was given this question.

Input program only with numbers 0-9. The first input must include the code {1,0,3,7,0,3,1,1}. Input must be equal to 15 digits. If it is wrong it will ask for user input again.

I have a problem in accepting only the numbers 0-9. When I input a wrong command like 10370311abcdefg, it will asks the user to input again. But if I input a correct one like 10370311456789, it also will ask the user to input again which should be stopped. The printf for the correct answer does not come out.

Here this code:

int main() {

    char nim[16];
    char kode[8] = {'1', '0', '3', '7', '0', '3', '1', '1'};
    do {
        printf("NIM = ");
        gets(nim);
        int panjang = strlen(nim);
        int benar = 0;
        bool cekang =false;
        for (int i = 0; i < 8; i++) {
            if(nim[i] != kode[i]){
                benar = 1;
              break;
            }
        }
        
        if (panjang < 15) {
            printf("Kurang dari 15!\n");
        }else if(panjang > 15){
            printf("Lebih dari 15\n");
        }else if(panjang == 15 && benar == 1){
            printf("All Required Characters not present\n");
        }else if(panjang == 15 && benar == 0){
             for(int i = 0;i < panjang;i++){
                if(!(nim[i] >= '0' && nim[i] <= '9')){
                 printf("hanya0-9\n");
                 cekang=false;break;
                }
            }
            
            if(cekang==true){
                printf("sucsess!\n");break;
            }
            
        }
    } while (true);
}
Ramesh-X
  • 4,853
  • 6
  • 46
  • 67
  • [Never use gets](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used). As it is, your code has undefined behaviour when the user enters a string that is longer than 15 characters (including newline character). After that `nim` overflows. So you should change `gets` to `fgets` and use a different way to check whether the entered string is too lone (it will not end with a newline character in that case). – kaylum Mar 07 '21 at 02:51
  • Unrelated general recommendation: don't compare `bool`s with the constants. Use appropriate names (no idea what ´cekang´ means, but ´success´ would be a good name) like adjectives or similar and just write `if ( cekang )`. This will make the code easier readable being closer to natural (English) language. The coparisson otoh will require the brain to stop and evaluate the comparison explicitly. This is a psychological effect, fyi. – too honest for this site Mar 07 '21 at 03:03

1 Answers1

0

The problem is that your "cekang" variable is never true because you are initializing it with false. You should initialize it with true.

Initialize cekeng variable like this

bool cekang = true;
Haseeb Ahmad
  • 118
  • 1
  • 13