Home > Mobile >  C while loop using scanf prints twice when entering more than 1 char of input
C while loop using scanf prints twice when entering more than 1 char of input

Time:11-29

I'm trying to read input from stdin in C, where the program performs a few tasks if the entered character is any key but "enter". I'm using a while loop, and it works fine when user only enters 1 char, but prints a line twice when they enter more than that (entering more than 1 char is fine, the program should generate a new number per each one -- so like if the user enters 'aaa', it generates 3 new numbers.)

So this is the ideal output after entering something like 'eeee'(and it works fine when you enter just one char):

CallList: I22 U55 U52 L1
enter any key for call (q to quit, no enter):

but this is what actually happens when you enter 'eeee':

enter any key for call (q to quit, no enter): CallList: I22 U55 U52 L1
enter any key for call (q to quit, no enter):

and this is the part of my code (minimal reproducible version):

#include <stdio.h>
#include <stdlib.h>
int main(void){

system("clear");
  printf ("CallList: \n");
  printf("enter any key for call (q to quit, no enter): ");
char c;
  scanf(" %c", &c);
  system("clear");

char quit = 'q';
  int random;
  srand(1063);

  while (c != quit){

    if (c != '\n') {
      random = rand() % 75   1;
      // does a few functions here, they don't print anything and don't use stdin
     }
    printf ("CallList: ");
    // prints the call list here
    printf("\n");
    printf("enter any key for call (q to quit, no enter): ");
    scanf(" %c", &c);
    system("clear");
    }
printf("Goodbye! \n");
  exit(0);

}

what is causing this and how can I fix it?

CodePudding user response:

Try this in your loop:

    while (c != quit){
 
        if (c != '\n') {
            random = rand() % 75   1;
            //here you can add things to your calllist
            c = getchar();
        }
        else {
            printf ("CallList: ");
            // prints the call list here
            printf("\n");
            printf("enter any key for call (q to quit, no enter): ");
 
            c = getchar();
            system("clear");
        }
    }
  • Related