Kyrol
Kyrol

Reputation: 3607

"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?

Upvotes: 0

Views: 1234

Answers (4)

bashrc
bashrc

Reputation: 4835

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.

Upvotes: 0

MOHAMED
MOHAMED

Reputation: 43518

you have to use

scanf("%s", choice);

instead of

scanf("%s", &choice);

Upvotes: 1

ravenspoint
ravenspoint

Reputation: 20472

Change

scanf("%s", &choice);

to

scanf("%s", choice);

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753735

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.

Upvotes: 3

Related Questions