为什么我的getchar()不能在这里工作?

时间:2014-02-27 23:20:18

标签: c getchar

在我的计划中,我只是计算事物的成本。但是,最后我想在程序中稍微休息,要求用户只需按下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);
}

2 个答案:

答案 0 :(得分:0)

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

您可能希望将程序更改为使用getline。还有其他关于如何在How to read a line from the console in C?

编写get行的示例

答案 1 :(得分:0)

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

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

然后键入“\ n”,并将“123 \ n”赋予stdin

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

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

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

然后输入“\ n”,并将“456 \ n”输入stdin

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

最后,您拨打getchar()并填充,它会从\n读取上一行的stdin


那么该怎么办我停止程序在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); 

检查来自NULL的{​​{1}}返回值对于测试关闭的fgets()非常有用。
使用stdin的错误检查优于strtol()

相关问题