Search code examples
cscanfgetchar

How do I clear the new line \n after reading a character?


My main function is printing twice after I come from a function back to main().

I'm pretty sure when it comes back to main it runs the cycle if I input '\n' and I'm not being able to fix this.

int main(){
char faz;

printf("What do you want to do?\nWrite C to create\nWrite R to read\nWrite U to edit\nWrite D to delete\nWrite E to exit the program\n>");
while((faz = getchar()) != EOF || faz != '\n')
{
  if(faz=='C') escreve();
  if(faz=='R') ler();
  if(faz=='U') editar();
  if(faz=='D') apagar();
  if(faz=='E') exit(1);
  else{ main();}
}

Any help would be welcome, this is a simple library management program.


Solution

  • you are recursively calling your main and that is what causes the problem, and you are calling exit(1) that normally signals an error for a normal behavior. I suggest you do the following :

    int main(){
     char faz;
     bool done=false;
     printf("What do you want to do?\nWrite C to create\nWrite R to read\nWrite U to edit\nWrite D to delete\nWrite E to exit the program\n>");
     while(((faz = getchar()) != EOF || faz != '\n') && (!done))
     {
        done=true;
        if(faz=='C') escreve();
        if(faz=='R') ler();
        if(faz=='U') editar();
        if(faz=='D') apagar();
        if(faz=='E');
        else{ 
            done=false;
            printf("Please enter a valid input\n");
        }
    
     }
     return 0;
    }