Pengibaby
Pengibaby

Reputation: 373

In C, why do I only need getchar() to remove characters sometimes?

I am trying to use 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..
    }
}

Upvotes: 0

Views: 1133

Answers (2)

Gardener
Gardener

Reputation: 2660

It seems that you are scanning for a string rather than an int, and as such, you are passing in an int rather than the address of an int.

Change this line

   if(scanf("%[^\n]s", vigencipherkey) != 1){

To

  if (scanf("%d", &vigencipherkey) != 1) {

Upvotes: 1

chqrlie
chqrlie

Reputation: 145287

In order to read the remainder of the line input by the user, you can use this function:

int flush_line(void) {
    int c;
    while ((c = getchar()) != EOF && c != '\n')
        continue;
    return c;
}

Notes:

  • c must be defined as int to accommodate for all values of the type unsigned char and the special negative value EOF.
  • you should test for '\n' and EOF otherwise you will have an endless loop on premature end of file without a trailing newline, such as would occur if you redirect the input of your program from an empty file.
  • you can test for end of file by comparing the return value of flush_line() with EOF.

Upvotes: 0

Related Questions