【问题标题】:C program briefly shows on console, then disappearsC 程序在控制台上短暂显示,然后消失
【发布时间】:2016-09-14 00:17:42
【问题描述】:

我有 java 背景,但我是 C 编程新手,这是我的第一个硬件任务,如果这是一个简单的修复,请原谅我。我需要问一个客户他们的名字是什么以及他们想买什么。我是这样开始的:

#include <stdio.h>
#include <stdlib.h>
#define TSHIRT  18.95
#define CHIPS   1.79
#define COKE    2.99
#define TAX     0.06
#define DEPOSIT 1.20

int main(void) {
printf("Hello customer! What shall I call you?");

char name[20];
scanf("%s",name);
printf("Okay %s, here is what we have to offer:",name);
return EXIT_SUCCESS;
}

程序运行时,它只会在控制台上短暂显示,然后消失,控制台为空白。这是什么原因?

【问题讨论】:

标签: c console


【解决方案1】:

您在语句结束时返回,我假设您使用的是 Visual Studio,它将在应用程序完成运行时终止控制台。您可以做的一件事是在返回之前添加一个断点,或者更简单的方法是使用 getch() 来伪造它,例如

#include <stdio.h>
#include <stdlib.h>
#define TSHIRT  18.95
#define CHIPS   1.79
#define COKE    2.99
#define TAX     0.06
#define DEPOSIT 1.20

int main(void) {
printf("Hello customer! What shall I call you?");

char name[20];
scanf("%s",name);
printf("Okay %s, here is what we have to offer:",name);
getch();
return EXIT_SUCCESS;
}

如果这不起作用,请添加 include conio.h,但我相信没有它也可以。

#include <conio.h>

此外,为了帮助您避免缓冲区溢出,您应该像这样使用 scanf:

scanf("%19s",name);

您不想扫描超过分配的缓冲区,您应该使用缓冲区长度减一,因为 scanf 会在扫描末尾附加一个空终止符。

【讨论】:

    【解决方案2】:

    进行以下细微更改:

    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>  // It contains information of getch() function which we used later in program
    #define TSHIRT  18.95
    #define CHIPS   1.79
    #define COKE    2.99
    #define TAX     0.06
    #define DEPOSIT 1.20
    
    int main(void) {
    printf("Hello customer! What shall I call you?");
    
    char name[20];
    scanf("%s",name);
    printf("Okay %s, here is what we have to offer:",name);
    getch();   // It will wait for one char input from user
    return EXIT_SUCCESS;
    }
    

    getch() 等待并保持屏幕,直到您输入任何单个字符。 希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多