简体   繁体   English

做……在 C 中终止程序

[英]Do…while in C to terminate a program

I am using do...while as a loop control in C language.我正在使用 do...while 作为 C 语言中的循环控制。 I need to terminate the program when the user enters "99", else the user should guess the number to terminate the program, until then the program will run.当用户输入“99”时我需要终止程序,否则用户应该猜测终止程序的数字,直到程序运行为止。 Here is the code.这是代码。 I don't have any compiler error, but instead it prints the number 0 to the number the users entered.我没有任何编译器错误,而是将数字 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;
}

Any help is appreciated.任何帮助表示赞赏。

scanf is not like Python's input , for example.例如, scanf不像 Python 的input It requires the exact input that you specify in the format string.它需要您在格式字符串中指定的确切输入。 In your particular case, you are expecting the users to enter "Enter the magic number to terminate this program: ", followed by a number.在您的特定情况下,您希望用户输入“输入幻数以终止此程序:”,后跟一个数字。

One way to check this is to use the return value, which tells you the number of matched arguments:检查这一点的一种方法是使用返回值,它告诉您匹配的 arguments 的数量:

k = scanf("...\n", &num);
printf("scanf managed to get %d inputs\n", k);

The solution is to split the input and output portions:解决方案是拆分输入和 output 部分:

printf("Enter the magic number to terminate this program: ");
scanf("%d", &num);

scanf will automatically filter out whitespace between inputs, including the newlines that the user enters. scanf将自动过滤掉输入之间的空格,包括用户输入的换行符。 You can also consume those explicitly with either "%d\n" or equivalently "%d " .您还可以使用"%d\n"或等效的"%d "显式使用它们。 However, you shouldn't do that.但是,您不应该这样做。 scanf treats any whitespace characters as "any number of whitespace", and will block until it receives the next non-whitespace character. scanf将任何空白字符视为“任意数量的空白”,并将阻塞直到它接收到下一个非空白字符。 It will also cause a problem if your stream ends without a trailing newline.如果您的 stream 结尾没有尾随换行符,也会导致问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM