简体   繁体   English

“带有printf的scanf”与“带有printf的fget”

[英]“scanf with printf” vs “fgets with printf”

I know about the difference and the advantage/disatvantage of using scanf and fgets . 我知道使用scanffgets的区别以及优点/缺点。

I don't understand the relations between printf and this two C standard functions. 我不了解printf与这两个C标准函数之间的关系。

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; 如果我使用fgetsprintf在stdout上正确打印结果;

If I use scanf , printf ` doesn't print anything on stdout. 如果我使用scanfprintf`不会在stdout上打印任何内容。

Why this behaviour? 为什么这种行为?

You used scanf("%s", &choice); 您使用了scanf("%s", &choice); which passes a char ** to scanf() when it expects a char * . 当期望char *时,将char **传递给scanf()

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); 更改此scanf("%s", &choice); to this scanf("%s", choice); 到这个scanf("%s", choice); will cause scanf and fgets to show almost similar behavior. 将导致scanf和fgets表现出几乎相似的行为。

scanf requires an address as an argument. scanf需要一个地址作为参数。 It goes on and stores the input from stdin after converting it based on the supplied format specifier. 根据提供的格式说明符将其转换后,它将继续并存储来自stdin的输入。 Here the format specifier is %s so it will try to store the input at the address pointed by address of choice . 此处的格式说明符为%s,因此它将尝试将输入存储在选择地址所指向的地址处 What you need here is the address from where the choice array will begin,which in this case is choice itself. 您需要的是选择数组的起始地址,在这种情况下,这就是选择本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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