0

First, I'm really sorry for the weird title as I don't know what's the best way to describe. I'm a self-learner in C and there is a problem when I try to print the character. Here is the code:

#include <stdio.h>

main()
{
int num;
float amt;
char ch;
long int pop_of_Indian;
printf("value of num: ");
scanf("%d", &num);
printf("value of amt: ");
scanf("%f", &amt);
printf("one character: ");
scanf("%c", &ch);
printf("Indian population: ");
scanf("%ld", &pop_of_Indian);

printf("NUM = %d\n AMT = %f\n Code = %c\n population of India is %ld\n", num, amt, ch, pop_of_Indian);
}

Everything runs smoothly until the code required the character from user: You can see the line requires character input from user is in the same line with Indian's population input requirement

However, when I run the character part separately, it runs normally:

#include <stdio.h>
main()
{
char ch;
printf("one character: ");
scanf("%c", &ch);
printf("Code = %c \n", ch);
}

What am I doing wrong here?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Nam
  • 9
  • 1
  • `scanf("%c", &ch);` --> `scanf(" %c", &ch);` skip previous white space(newline). – BLUEPIXY Jul 03 '16 at 03:18
  • Wow it works! Thank you a lot. Do you know why there is the difference between the code and the separate part below? There is no space in the below one but it works as well. – Nam Jul 03 '16 at 03:23
  • `scanf("%f", &amt);` : input 99.5with newline(enter). 99.5 into amt. newline into `ch` of `scanf("%c", &ch);`. – BLUEPIXY Jul 03 '16 at 03:26
  • You typed `123.25`, did you not? %f reads the 123.25 and the next %c reads the . – user253751 Jul 03 '16 at 04:12

0 Answers0