【发布时间】:2017-03-16 16:46:00
【问题描述】:
我需要做一份海鲜菜单作为我大学的作业。我将在这里提供相关代码:
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 有效时它不起作用?因为我输入的只是字符。请赐教。
【问题讨论】:
-
两种变体都会调用未定义的行为。请阅读
scanf的文档以及关于字符和字符数组 的区别。一个 C 字符串。 -
%c和%s的行为应该在您方便的 C 参考手册中清楚地说明。如果您没有方便的 C 参考手册,我推荐 Harbison & Steele 的 C: A Reference Manual。%c从输入流中读取 single 字符并将其存储到单个char对象中。%s从输入流中读取 sequence 字符值,直到它看到空格或 EOF 并将它们作为 0 结尾的字符串存储到char的 array 中。
标签: c arrays char scanf format-specifiers