问题描述
我试图让用户按 ENTER 键退出我的程序。我正在使用
(void) getchar();
getchar 函数等待用户按下 ENTER 键。这适用于不请求任何用户输入的简单 Hello world 程序,但在用户输入双精度的该程序中,该程序跳过了 getchar 命令。如果我双击“Lab 1B.exe”可执行代码,在用户输入三角形的双面A后,运行程序的可执行窗口消失(程序跳过getchar命令)。如何让程序等待用户输入 ENTER 键?
如何让程序等待用户输入任意键???
#include <stdio.h>
int main(void)
{
double a = 0,b = 0,c = 0;
//int x = 0;
double x = 0;
printf("Lab 1B - Triangles:\n\n");
printf("Enter the length of your triangle's side A: ");
scanf_s("%lf",&a);
printf("The length of the triangle's side A is: ");
printf("%lf",a);
printf("\n");
printf("\nPress the <ENTER> key to exit.\n");
(void) getchar();
//printf("\nEnter any value to exit: ");
//scanf_s("%i",&x);
//scanf_s("%lf",&x);
return 0;
}
解决方法
scanf()
留下一个尾随 newline
字符,稍后您的 getchar()
调用会使用该字符。如果您总是通过用户而不是重定向或其他 FILE 流获取输入,则您可以在 getchar()
调用之后再次调用 scanf()
。您应该在此 here 上查看更多 scanf()
的结果。
#include <stdio.h>
int main(void)
{
double a = 0,b = 0,c = 0;
double x = 0;
printf("Lab 1B - Triangles:\n\n");
printf("Enter the length of your triangle's side A: ");
if (scanf("%lf",&a) != 1) /* scanf_s behaves similar in terms of the return value */
{
fputs("error msg",stderr);
return -1;
}
getchar(); /* consuming the leftover newline */
printf("The length of the triangle's side A is: %lf\n",a);
printf("\nPress the <ENTER> key to exit.\n");
while (getchar() != '\n') /* waiting for newline input */
;
return 0;
}
另外一种更好的方法是,您可以使用 fgets()
从用户处以字符串形式获取输入,然后使用 sscanf()
对其进行解析。
#include <stdio.h>
#define MAX_SIZE 500
int main(void)
{
char buff[MAX_SIZE] = {0};
double a = 0,c = 0;
double x = 0;
printf("Lab 1B - Triangles:\n\n");
printf("Enter the length of your triangle's side A: ");
fgets(buff,MAX_SIZE,stdin);
if (sscanf(buff,"%lf",&a) != 1)
{
fputs("error msg",stderr);
return -1;
}
printf("The length of the triangle's side A is: %lf\n",a);
printf("\nPress the <ENTER> key to exit.\n");
while (getchar() != '\n')
;
return 0;
}
,
问题是因为 Grandson
函数只读取非空格或非换行符。执行 #include <iostream>
template <typename T>
class Base {
protected:
virtual void work() {
T a;
std::cout << "From Base" << '\n';
}
public:
virtual void call() = 0;
};
template <typename T>
class Child : public Base<T> {
public:
virtual void call() override {
Base<T>::work(); // Problem Here
// work();
}
};
template <typename T>
class Grandson : public Child<T> {
protected:
void work() override {
std::cout << "From Grandson" << '\n';
}
};
int main() {
Grandson<int> g;
g.call();
}
后,第一个输入的 scanf
仍在缓冲区中。
当您再次调用 scanf()
时,它接受换行符并且程序终止。
修复它的一种简单方法是在 \n
之后再次调用 getchar()
以使用换行符。
另一种方法是在 scanf 中放置空格或换行符。 参考:https://www.geeksforgeeks.org/problem-with-scanf-when-there-is-fgetsgetsscanf-after-it/
getchar()