我正在自学C语言,目前正在学习Scanf和Printf函数。
我改编了这个程序来测试自己:
char topping[24];
int slices;
int day, year;
float cost;
char month[10];
printf(" How much does a pizza cost in your area?\n");
printf("$");
scanf(" %f", &cost);
printf("What is your favorite one-word pizza topping?\n");
scanf(" %s",topping);
printf("How many slices of %s pizza, topping can you eat in one sitting\n",topping);
scanf(" %d", &slices);
printf(" What is today's date (enter in the following format 1-Jan-2016 )\n");
scanf(" %d-%s-%d", &day, month, &year);
printf("\nWhy not treat yourself to dinner on %d-%s-%d and have %d slices of %s pizza ? It will only cost you %.2f", day, month, year,slices, topping,cost);
练习的目的是让我了解 scanf 函数以及它们的“微妙”程度。
我的测试程序运行良好...除了年份变量中的输出。
为什么年份变量中的输出会出现乱码,我该如何修复它?
谢谢。
最佳答案
问题就在这里。 %s
说明符表示读取直到下一个空格的任何字符。因此,在 %d-
匹配 1-
后,%s
匹配 Jan-2016
。然后下一个 %d
失败,因为没有任何内容可以匹配。
首先,您应该始终检查 scanf
的返回值,以便了解是否存在匹配失败。例如本例中:
if ( 3 != scanf(" %d-%s-%d", &day, month, &year) )
{
printf("Matching failure occurred.\n");
// do something else...
}
else
{
printf("Why not treat yourself...
其次,要切实避免问题。如您所见,scanf
函数非常有限。要使用其他分隔符代替空格,可以使用 scanset 说明符 %[.....]
代替:
scanf(" %d-%9[^-]-%d", &day, month, &year)
(具有相同的错误检查)。 scanset 说明符意味着读取与 []
内的字符匹配的任何字符(可能包括空格),但 ^
指示不匹配下一个字符。因此,这将读取所有内容,直到下一个 -
。此外,我添加了 9
以避免溢出大小为 9+1
的缓冲区。
当然,这意味着如果这个人不再输入另一个-
,那么程序就会变得有点奇怪。您可以通过使格式字符串变得越来越复杂来解决这个问题;或者您可以使用 fgets
读取整行,然后将 sscanf
函数与上述字符串一起使用。这将捕获用户在输入另一个 -
之前按 Enter 的情况。
事实上,事实证明,一次读取一整行,然后返回并处理该行通常是一个好主意。
在某个阶段,您会厌倦 scanf
的糟糕程度,并制作自己的解析器。
关于c - C 中的 Scanf/Printf...这是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39315581/