[英]How to use printf() and scanf() in C without going to the next line?
[英]Scanf/Printf in C…what's going on here?
我正在自学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功能的理解,以及它们的“微妙程度”。
我的测试程序在这里运行良好...除了year变量中的输出。
为什么年份变量中的输出会吐出乱码,我该如何解决?
谢谢。
这是问题所在。 %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
糟糕程度,并创建自己的解析器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.