NO

Author Topic: scanf for char doesn't work  (Read 3197 times)

puredesi5

  • Guest
scanf for char doesn't work
« 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;
}

Offline jj2007

  • Member
  • *
  • Posts: 536
Re: scanf for char doesn't work
« Reply #1 on: April 15, 2013, 01:17:39 AM »
   scanf ("%d", &income);

puredesi5

  • Guest
Re: scanf for char doesn't work
« Reply #2 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.

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Re: scanf for char doesn't work
« Reply #3 on: April 15, 2013, 06:03:26 AM »
the issue is with
   scanf ("%c",&marital_status);
Code: [Select]
scanf (" %c",&marital_status);or
Code: [Select]
scanf ("%*c%c",&marital_status);to handle LF in input stream.
May the source be with you

puredesi5

  • Guest
Re: scanf for char doesn't work
« Reply #4 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!