【问题标题】:Why is my getchar() not working here?为什么我的 getchar() 在这里不起作用?
【发布时间】: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", &amp;hotels) != 1) { ...report error... } 使用scanf() 进行转换并检查没有错误。
  • getchar(); --> getchar();getchar();
  • @BLUEPIXY:只要用户没有在数字后意外添加空格...:D 对于预期的输入,这将起作用。

标签: c getchar


【解决方案1】:

我最好的猜测是它在用户输入输入后检索剩余的换行符。您可以打印出返回值进行验证。如果我是正确的,它将是“10”或“13”,具体取决于您的操作系统。

您可能想更改您的程序以使用 getline。还有其他关于如何在How to read a line from the console in C? 处编写获取行的示例

【讨论】:

  • 如果getchar() 读取一个换行符,它将返回'\n',通常等于10。在文本模式下,每个行结束符在输入时转换为单个换行符,并且每个换行符在输出时转换为行尾序列。 (在类 UNIX 系统上,转换是微不足道的。)
【解决方案2】:

当代码调用scanf("%s", ... 时,程序等待输入。

您键入“123”,但由于stdin 是缓冲输入并等待\n,因此系统没有向scanf() 提供任何数据。

然后你输入“\n”,“123\n”就给stdin

scanf("%s",...) 读取stdin 并扫描可选的前导空白,然后是非空白“123”。最后它看到“\n”并将其放回stdin并完成。

代码再次调用scanf("%s", ...scanf() 扫描“\n”作为其扫描可选前导空白的一部分。然后它等待更多的输入。

您键入“456”,但由于stdin 是缓冲输入并等待\n,因此系统没有向scanf() 提供任何数据。

然后你输入“\n”,“456\n”就给stdin

scanf("%s",...) 读取stdin 并扫描可选的前导空白,然后是非空白“456”。最后它看到“\n”并将其放回stdin中并完成。

最后你调用getchar() 并且噗,它从stdin 读取上一行的\n


那么我该怎么做才能停止程序在 getchar() 处请求输入,以及如何让它只识别一个输入按钮。

最佳方法:使用fgets()

char hotels_houses[5+1];

// scanf("%s", hotels_houses);
fgets(hotels_houses, sizeof hotels_houses, stdin);
houses = atoi(hotels_houses);
...
// scanf("%s", hotels_houses);
fgets(hotels_houses, sizeof hotels_houses, stdin);
hotels = atoi(hotels_houses);
...
puts("Click enter to calculate total cash ");
fgets(bhotels_houses, sizeof hotels_houses, stdin); // do nothing w/hotels_houses
printf("Total cost: %d\n", cost); 

检查来自fgets()NULL 返回值对于测试关闭的stdin 很有用。
使用strtol()atoi() 具有错误检查优势。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 2019-02-10
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多