Question

I know about the difference and the advantage/disatvantage of using scanf and fgets.

I don't understand the relations between printf and this two C standard functions.

I have this simple code:

 void print_choice(char * list, char * choice)
{
  /* check parameters */
  if(!list || !choice)
    return;

  printf("list of users: %s\n", list);
  printf("Choice -- ? ");

  /* scanf("%s", &choice); */
  /* fgets(choice, 20, stdin); */

}


int main()
{
  char choice[20];
  char * list = "marco:dario:roberto:franco";

  print_choice(list, choice);
  printf("choice = %s\n", choice);

  return 0;
}

if I use fgets, printf print the result correctly on stdout;

If I use scanf, printf` doesn't print anything on stdout.

Why this behaviour?

Was it helpful?

Solution

You used scanf("%s", &choice); which passes a char ** to scanf() when it expects a char *.

Drop the &.

If your compiler wasn't complaining, you either haven't turned on enough warnings or you need a better compiler.

OTHER TIPS

Change

scanf("%s", &choice);

to

scanf("%s", choice);

you have to use

scanf("%s", choice);

instead of

scanf("%s", &choice);

Changing this scanf("%s", &choice); to this scanf("%s", choice); will cause scanf and fgets to show almost similar behavior.

scanf requires an address as an argument. It goes on and stores the input from stdin after converting it based on the supplied format specifier. Here the format specifier is %s so it will try to store the input at the address pointed by address of choice . What you need here is the address from where the choice array will begin,which in this case is choice itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top