Char in c problem

Asked

Viewed 26 times

-1

Good evening guys I’m here with a problem that automatically my value is read on IS() anyone know why this is happening? can’t find the error.

       if((con1 != 0) && (con2 != 0) && (con3 != 0) && (con4 != 0) && (con5 != 0))
{
    printf("\n---------------------------------------------------------");
    printf("\nJa usou todas as opçoes quer continuar ? : ");
    scanf("%c", &opt);

    if((opt == 's'))
    {
         system("cls");
    }

    else if((opt == 'n'))
    {
       return 0;
    }

    else{
        printf("\nErro, introdusa outra vez : ");
        scanf("%c", &opt);
    }

    }

inserir a descrição da imagem aqui

  • 1

    You can’t say for sure with just this snippet of code but, apparently, that’s the old problem with the dirty input buffer. Make sure there are no characters in the input buffer before your scanf.See ietm 12.26b of http://www.faqs.org/faqs/C-faq/faq/

  • I basically have to use this code?

  • while((c = getchar()) != ' n' && c != EOF) /* discard */ ;

1 answer

0

Basically solved my problem by adding another scanf

       if((con1 != 0) && (con2 != 0) && (con3 != 0) && (con4 != 0) && (con5 != 0))
           {
printf("\n---------------------------------------------------------");
printf("\nJa usou todas as opçoes quer continuar ? : ");
scanf("%c", &opt);
scanf("%c", &opt);

if((opt == 's'))
{
     system("cls");
}

else if((opt == 'n'))
{
   return 0;
}

else{
    printf("\nErro, introdusa outra vez : ");
    scanf("%c", &opt);
}

}
  • Whereas you can ensure that the character that was left in the input buffer is a ' n" I think it would be simpler to do scanf(" %c", &opt);, note the space before the %c consuming the ' n'.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.