gpt4 book ai didi

c - %c 与 %s 的实际差异

转载 作者:行者123 更新时间:2023-11-30 21:23:37 25 4
gpt4 key购买 nike

我在大学里需要做一份海鲜菜单作为作业。我将在这里提供相关代码:

 int main ()
{
int a,d;
float c ;
char b,s,S,m,M,l,L;

printf ("\n\t\t\t\tSeafood Menu\n");
printf ("----------------------------------------------------------------------------------\n");
printf ("\t\t\t\t\t\t Dish Size\n");
printf ("Item Number\t Seafood Dish\t Small\t Medium Large\t\n");
printf ("----------------------------------------------------------------------------------\n");
printf ("\t 1\t Fried \t20.00 \t\t 40.00 \t\t 55.00\n");
//Continue with a bunch of menu here

printf (" Enter item number :");
scanf ("%d",&a);
printf (" Enter dish size (S/M/L) :");
scanf ("%s",&b);


if ((a==1)&&((b=='s')||(b=='S')))
{c=20.00;}
//continue with a bunch of condition to choose the price per dish stated in the menu


printf (" Enter dish quantity :");
scanf ("%d",&d);
printf (" Price per dish size :RM%.2f\n\n\n",c);


return 0;
}

当我尝试将其中的格式标识符更改为 %c 时,它只是停止接受该特定 scanf 的输入。

printf ("Enter dish size (S/M/L):");
scanf ("%s",b);

我想附上图片,但似乎不允许我这样做,所以留下两个链接:

Normal, using %s:abnormal, using %c

我很好奇为什么当我使用 %c 时它不起作用,而 %s 可以工作?我输入的只是字符。请赐教。

最佳答案

I'm curious about why it doesn't work when I use %c while %s works?

好吧,你猜怎么着,即使看起来有效,它也不起作用。

正如手册页中提到的,对于 scanf(),参数的类型是

  • %c 需要一个指向 char
  • 的指针
  • %s 需要一个指向 char 数组的初始元素的指针。

引用 C11,第 §7.21.6.2 章,(强调我的)

c Matches a sequence of characters of exactly the number specified by the field width (1 if no field width is present in the directive).

If no l length modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence. No null character is added.

s Matches a sequence of non-white-space characters.

If no l length modifier is present,the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically.

就你而言,

  • 提供 %s 是错误的,因为单个 char 是一个太短而无法扫描和保存数组的元素,即以 null 结尾的元素。这会导致undefined behavior当内存溢出发生时。

  • %c 应该有 "worked" ,如果输入流没有从之前的 存储的 newline按下 ENTER 键。如果您清除所有待处理输入的输入流,您将看到它有效。使用类似的东西

    scanf(" %c", &b);   //the whitespace "eats up" all the previous whitespaces

    您可以看到this previous answer我的,有关相同的详细信息。

关于c - %c 与 %s 的实际差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42840090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com