简体   繁体   English

C中的无限循环代码

[英]Infinite loop code in C

In the below program I try to input a number between 1 to 100 but if I enter a 'character' or "string" ( like s or sova ) during the execution time of scanf() statement it creates a infinite loop. 在下面的程序中,我试着输入之间的数字1100 ,但如果我输入a 'character'"string" (如S或sova中的执行时间) scanf()声明它创建了一个无限循环。 so I try to do .... when I input a string or a character it shown me a message like "wrong value entered. enter again" and it will enter again... 所以我试着做....当我输入一个字符串或一个字符时,它向我显示一条消息,例如“输入了错误的值。再次输入”,它将再次输入...
Thanx; 感谢名单;

#include<stdio.h>
int main()
{
    int a;
    scanf("%d",&a);
    while(!(a>=1&&a<=100))
    {
        printf("wrong value entered. enter again\n");
        scanf("%d",&a);
    }
    printf("you enter %d. Thanxz",a);
    return 0;
}
  1. You need to check the return value of scanf 您需要检查scanf的返回值
  2. If the user has not entered a integer, you need to eat the input. 如果用户没有输入整数,则需要输入输入。 The scanf function will continually say not a integer, try again. scanf函数将不断说不是整数,请再试一次。 So if scanf returns 0 you need to deal with it 因此,如果scanf返回0,则需要处理它

When you use scanf you are working with buffered input, this means that when you enter a value say "123" and press ENTER then "123" plus the ending character (ENTER) will all be added to the buffer. 当您使用scanf时,您正在使用缓冲输入,这意味着当您输入值“123”并按ENTER时,“123”加上结束字符(ENTER)将全部添加到缓冲区。 scanf then removes 123 since %d specifies that an integer should be read but if a user enters something invalid like a string instead then the buffer will not be emptied. 然后scanf删除123,因为%d指定应该读取整数,但如果用户输入的内容像字符串一样无效,则缓冲区将不会被清空。

A better way to read input from the keyboard is to use fgets() where you specify a max length to read. 从键盘读取输入的更好方法是使用fgets(),您可以在其中指定要读取的最大长度。 Once you have the input you can use sscanf() to retrieve the numeric value from it. 输入后,您可以使用sscanf()从中检索数值。 The ENTER till then not irritate your input. ENTER直到那时不会激怒你的输入。

char buffer[128];
fgets( buffer, 128, stdin );
sscanf( buffer, "%d", &a );

Also always check return values from functions as a rule of thumb so that you can do appropriate action if the function fails. 还要始终根据经验检查函数的返回值,以便在函数失败时执行适当的操作。

Try this. 尝试这个。

#include <stdio.h>
#define FLUSH while (getchar() != '\n')  // macro to eat invalid input

int main (void) {

    int a = 0;
    printf ("Enter an integer: ");
    scanf("%d", &a);

    while (a < 1 || a > 100) {

        FLUSH;
        printf("Invalid input. Please try again: ");
        scanf("%d",&a);
    }

    printf("You entered %d.\nThanks!\n", a);
    return 0;
}

Your code shows several coding habits that need to be changed: 您的代码显示了需要更改的几种编码习惯:

  1. Include (void) in the parameter list of main() . main()的参数列表中包含(void) main()
  2. Leave spaces on either side of binary operators: while(!(a>=1&&a<=100)) is needlessly ugly and hard to read. 在二元运算符的两边留下空格: while(!(a>=1&&a<=100))是不必要的丑陋和难以阅读。
  3. Simplify your logical expressions. 简化您的逻辑表达式。 Why use (! (a>=1 && a<=100)) when it means the same thing as (a < 1 || a > 100) , and the latter is so much easier to read? 为什么使用(! (a>=1 && a<=100))当它意味着与(a < 1 || a > 100)同时,后者更容易阅读?
  4. Prompt for user input when needed. 需要时提示用户输入。 Don't have the cursor just sit at a blank line with no indication to the user about what to do. 没有光标只是坐在一条空白行,没有指示用户该做什么。
  5. Use proper grammar and capitalization in your prompts. 在提示中使用正确的语法和大小写。 There's no reason to be lazy in your programming. 你的编程没有理由懒惰。

If the return value from scanf is not equal to the number of item you like the user to input, read all characters of the input buffer until there is a '\\n'. 如果scanf的返回值不等于您希望用户输入的项目数,请读取输入缓冲区的所有字符,直到有'\\ n'为止。 But instead of copying a whole loop over and over again to the places in your code where the user should input something, you could wrap the loop in a function like this: 但是,不是将一个完整的循环一遍又一遍地复制到代码中用户应该输入内容的位置,而是可以将循环包装在这样的函数中:

#include <stdio.h>
#include <stdarg.h>
#include <string.h>

void input(const char *format,...)
{
    va_list ap;
    int r;
    /* number of items [to read] */
    int noi=0;

    for(r=0;r<strlen(format)-1;r++)
    {
        if(format[r]=='%')
        {
            if(format[r+1]!='%')
                noi++;
            else
                r++;
        }
    }

    do
    {
        va_start(ap,format);
        r=vscanf(format,ap);
        va_end(ap);

        if(r!=noi)
        {
            switch(r)
            {
                case EOF:
                case 0:
                    printf("All wrong, try again!\n");
                break;

                default:
                    printf("Unexpected value after item no %d!\n",r);
            }

             while(getc(stdin)!='\n');
        }
        else
            break;

    } while(1);
}

Hope that helps, 希望有所帮助,

Jan 一月

why are you using a loop, your logic seems that it must have a if ---else condition 为什么你使用循环,你的逻辑似乎必须有一个if --- else条件

while (1)
 {
    if (a>=1&&a<=100)
    {
        printf("wrong value entered. enter again\n");
        scanf("%d",&a);
    }
    else 
    {
         printf("you enter %d. Thanxz",a);
         return 0;
    }
}

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

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