Pelles C forum

C language => Beginner questions => Topic started by: puredesi5 on April 14, 2013, 10:51:43 PM

Title: scanf for char doesn't work
Post by: puredesi5 on April 14, 2013, 10:51:43 PM
I can't see anything wrong with this code but for some reason, scanf for char doesn't work. Any idea?

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("Hello, world!\n");

   double income, intrest;
   char marital_status;

   printf ("How much did you earn this year? ");
   scanf ("%lf", &income);
   if (income > 100.00)
   {
      printf ("Please enter M=married or S=Single for marital status: ");
      scanf ("%c", &marital_status);
      printf ("How much intrest did you earn this year? ");
      scanf ("%lf", &intrest);
      printf ("your marital status is %c and your income is %.2lf intrest is %.2lf \n",marital_status, income,intrest);
   }
    return 0;
}
Title: Re: scanf for char doesn't work
Post by: jj2007 on April 15, 2013, 01:17:39 AM
   scanf ("%d", &income);
Title: Re: scanf for char doesn't work
Post by: puredesi5 on April 15, 2013, 02:08:56 AM
%d is for int data type. Also, the issue is with
   scanf ("%c",&marital_status);
not with other data type.
Title: Re: scanf for char doesn't work
Post by: TimoVJL on April 15, 2013, 06:03:26 AM
Quote from: puredesi5 on April 15, 2013, 02:08:56 AMthe issue is with
   scanf ("%c",&marital_status);
scanf (" %c",&marital_status);orscanf ("%*c%c",&marital_status);to handle LF in input stream.
Title: Re: scanf for char doesn't work
Post by: puredesi5 on April 15, 2013, 04:58:37 PM
Thanks timovji! It worked.
I checked so many books and online but either they didn't address it or I didn't recognize. Also, the odd thing is same exact code would work if you bring it outside of the if block but would not work when it's in the if block.
Would someone please point me where can I get more information on why it works outside of the if block but not in the if block.
I really appreciate this forum and people who take time to respond.
Once again, thanks!