[英]Do…while in C to terminate a program
我正在使用 do...while 作为 C 语言中的循环控制。 当用户输入“99”时我需要终止程序,否则用户应该猜测终止程序的数字,直到程序运行为止。 这是代码。 我没有任何编译器错误,而是将数字 0 打印到用户输入的数字。
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num = 0;
do {
scanf("Enter the magic number to terminate this program: %d\n", &num);
printf("You entered : %d\n", num);
num++;
} while (num != 100);
printf("\nThe magic number is correct and the program is terminated:");
return 0;
}
任何帮助表示赞赏。
例如, scanf
不像 Python 的input
。 它需要您在格式字符串中指定的确切输入。 在您的特定情况下,您希望用户输入“输入幻数以终止此程序:”,后跟一个数字。
检查这一点的一种方法是使用返回值,它告诉您匹配的 arguments 的数量:
k = scanf("...\n", &num);
printf("scanf managed to get %d inputs\n", k);
解决方案是拆分输入和 output 部分:
printf("Enter the magic number to terminate this program: ");
scanf("%d", &num);
scanf
将自动过滤掉输入之间的空格,包括用户输入的换行符。 您还可以使用"%d\n"
或等效的"%d "
显式使用它们。 但是,您不应该这样做。 scanf
将任何空白字符视为“任意数量的空白”,并将阻塞直到它接收到下一个非空白字符。 如果您的 stream 结尾没有尾随换行符,也会导致问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.