简体   繁体   English

无限循环 Do While

[英]Infinite loop Do While

I am trying to create a program, in which at the beginning it shows a menu to the user, which consists in a do{... }while;我正在尝试创建一个程序,在开始时它会向用户显示一个菜单,该菜单包含在 do{... }while; which reads an int., with a switch inside.它读取一个 int.,里面有一个 switch。

It works perfectly to read and check the integer, the problem is when writing a character or string, which gets stuck in an infinite loop showing the default message of the switch loop.它可以完美地读取和检查 integer,问题是在写入字符或字符串时,它卡在无限循环中,显示开关循环的默认消息。 The code is as follows:代码如下:

int op;
printf("Choose an option:\n 1. option 1\n 2. option 2\n 3. option 3\n");
do{
    scanf("%d", &op);
    switch(op){
        case 1: (instruction); break;
        case 2: (instruction); break;
        case 3: (instruction); break;
        default: printf("\nPlease enter a valid option\n");
    }
}while(op<1 || op>3);

It works perfectly to read and check the integer, the problem is when writing a character or string, which gets stuck in an infinite loop showing the default message of the switch loop.它可以完美地读取和检查 integer,问题是在写入字符或字符串时,它卡在无限循环中,显示开关循环的默认消息。

scanf("%d", &op); does nothing when the input is not a valid int, you need to check the return value is 1 and if not to decide what to do like for instance read a string or flush up to the end of line, also managing the EOF case当输入不是有效的 int 时不执行任何操作,您需要检查返回值是否为 1,如果不决定要执行的操作,例如读取字符串或刷新到行尾,还需要管理 EOF 情况

Note in case scanf does nothing op is not set请注意,如果scanf什么都不做,则未设置op

So can be:所以可以:

int op;
printf("Choose an option:\n 1. option 1\n 2. option 2\n 3. option 3\n");
do{
    if (scanf("%d", &op) != 1) {
       // flush all the line
       while ((op = getchar()) != '\n') {
         if (c == EOF) {
           puts("EOF, abort");
           exit(0); /* what you want */
         }
       }
       op = -1; /* invalid value */
     }
     switch(op){
        case 1: (instruction); break;
        case 2: (instruction); break;
        case 3: (instruction); break;
        default: puts("\nPlease enter a valid option");
       }
    }           
}while(op<1 || op>3);

I encourage you to never trust on an input and always check return value of scanf etc我鼓励您永远不要相信输入并始终检查scanf等的返回值

The %d conversion specifier is seeking for decimal input only. %d转换说明符仅寻求十进制输入。 It does not work to consume characters or strings.使用字符或字符串不起作用。 If you input a character instead of an decimal value, the directive will fail, and because op isn´t initialized you have undefined behavior .如果您输入一个字符而不是一个十进制值,该指令将失败,并且由于op未初始化,您有未定义的行为

To catch a string with scanf() use the %s conversion specifier or use fgets() .要使用scanf()捕获字符串,请使用%s转换说明符或使用fgets() For only catching one character use the %c conversion specifier with scanf() .对于仅捕获一个字符,请使用带有scanf()%c转换说明符。

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

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