【发布时间】:2014-02-27 23:20:18
【问题描述】:
在我的程序中,我只是在计算事物的成本。但是,最后我想在程序中稍作休息,要求用户只需按下 Enter 按钮。我认为 getchar() 可以在这里工作,但它甚至不会停止,它只是继续打印。我什至尝试在 scanf("%s") 等稀少的格式之后放置一个空格。
所以有两件事我如何停止程序在 getchar() 处请求输入,以及如何让它只识别一个输入按钮。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char hotels_houses[5];
int houses, hotels, cost;
printf("Enter amount of houses on board: \n");
scanf("%s", hotels_houses);
houses = atoi(hotels_houses);
printf("Enter amount of hotels on board: \n");
scanf("%s", hotels_houses);
hotels = atoi(hotels_houses);
printf("Cost of houses: %d\n", houses);
printf("Cost of hotels: %d\n", hotels);
cost = (houses *40) + (hotels * 115);
puts("Click enter to calculate total cash ");
getchar(); /* just a filler */
printf("Total cost: %d\n", cost);
return(0);
}
【问题讨论】:
-
你无法判断它是否有效,因为你没有测试结果。这是工作;它在板上的酒店数量之后返回换行符(
scanf()留下输入中转换规范未读取的字符)。您可能会发现更容易阅读整行,然后使用sscanf()扫描它们。您应该考虑使用if (scanf("%d", &hotels) != 1) { ...report error... }使用scanf()进行转换并检查没有错误。 -
getchar();-->getchar();getchar(); -
@BLUEPIXY:只要用户没有在数字后意外添加空格...:D 对于预期的输入,这将起作用。