简体   繁体   中英

“scanf with printf” vs “fgets with printf”

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM