jeudi 28 mars 2019

C: Why do I only need getchar() to remove characters sometimes?

I need some help with explaining the use of getchar() to remove characters from the input buffer. In the following code, the user is asked to input a choice to select, and then depending on the choice, another input is required, either type int or type char (string). In the int case, getcar() is not needed and scanf takes in input correctly. But in the char case, scanf fails to get input without using getchar() beforehand. Is there a reason why that is?

printf("Available Ciphers:\n1) Caesar Cipher\n2) Vigenere Cipher\nSelected Cipher: ");
if(scanf("%d", &choice) != 1){
    printf("Error: Bad selection!\n");
    exit(EXIT_SUCCESS);
} else if (choice != 1 && choice != 2){
    printf("Error: Bad Selection!\n");
    exit(EXIT_SUCCESS);
//If the choice entered is correct, then run the following.
} else {
    if(choice == 1){
        printf("Input key as nuumber: ");
        if(scanf("%d", &caesarkey) != 1){ //Why is getchar() not needed here?
            printf("Error: Bad Key!\n");
            exit(EXIT_SUCCESS);
        }
        //morecode here
    } else if (choice == 2){
        printf("Input key as string: ");
        while(getchar() != '\n');  //Why is this needed here?
        /*Uses scanf and not fgets, since we do not want the
        key to contain the newline character '\n'. This is
        due to the fact that the newline character is not
        considered in the function that encrypts and decrypts
        plaintext and ciphertext.*/
        if(scanf("%[^\n]s", vigencipherkey) != 1){
            printf("Error, Cannot read inputted key!\n");
            exit(EXIT_SUCCESS);
        }
        //More code here..
    }
}

Aucun commentaire:

Enregistrer un commentaire