0

UPDATE scanf("%c ", &code); ==> scanf(" %c", &code); was the solution but i do not understand why

Hello, I have followed the format specifier rules and I tried to experiment with it but I still have the same problem it does not allow me to input MESSAGE= try to run this code written in C and you will see,

you can input any number tho. NUM = 5 population = 12345 the code part is a letter (%c) and message is a word atleast (%s)

thanks

#include <stdio.h>
int main(){
//Declare and initialize variables
int num;
float amt;
double pi;
long int pop_ph;
char code;
char msg[90];


printf("\n Enter the value of num: ");
scanf("%d", &num);
printf("\n Enter the value of amt: ");
scanf("%f", &amt);
printf("\n Enter the value of pi: ");
scanf("%e", &pi);
printf("\n Enter the population of Ph: ");
scanf("%ld", &pop_ph);
printf("\n Enter the value of code: ");
scanf(" %c", &code);
printf("\n Enter the message: ");
scanf("%s", msg);

printf("\n\n NUM = %d \n AMT = %f \n PI = %e \n POPULATION OF PH = %ld \n CODE = %c \n MESSAGE = %s", num, amt, pi, pop_ph, code, msg);
return 0;
}

  • 6
    Make `msg` larger. Do not use `&` on `msg` with `scanf`. Check the return value of `scanf`. – Paul Ogilvie Mar 01 '21 at 08:44
  • 1
    `scanf("%c ", &code);` ==> `scanf(" %c", &code);` – pmg Mar 01 '21 at 08:47
  • yes i tried that but still the same thanks for the response – Krent Mañacap Mar 01 '21 at 08:49
  • Suggestion: terminate your prints with a newline: `printf("...\n", ...);`... reason being the notion of "line" being `some characters followed by and including a newline`. – pmg Mar 01 '21 at 08:51
  • oh scanf("%c ", &code); ==> scanf(" %c", &code); this worked! thanks a lot!! but why?? – Krent Mañacap Mar 01 '21 at 08:51
  • 1
    Because `scanf("%c ", &code)` reads the `` from the previous input (the pop_h) into `code` then skips optional whitespace. Switching the `%c` and the space makes scanf **first** skip whitespace, then read a character. Note that `%s`, `%d` ... already include a **skip optional leading whitespace** by themselves (`%c`, `%[...]`, and `%n` do not skip whitespace). – pmg Mar 01 '21 at 08:55
  • Now that you've found the solution, you could answer your own question and mark it as accepted. It's perfectly fine and lets other users know that this issue has been solved – Jack Lilhammers Mar 01 '21 at 08:59
  • Do not use `%c` as an input formatter unless you fully understand what means *does not skip over white space characters*. Use `char code[2];`, `scanf("%s", code);` and use `code[0]` later. It is much more consistant with the other input formatters. – Serge Ballesta Mar 01 '21 at 08:59

0 Answers0