Infinite loop code in C

回眸只為那壹抹淺笑 提交于 2019-12-11 03:39:06

问题


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. 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:


  1. You need to check the return value of 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. So if scanf returns 0 you need to deal with it



回答2:


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 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.

A better way to read input from the keyboard is to use fgets() where you specify a max length to read. Once you have the input you can use sscanf() to retrieve the numeric value from it. The ENTER till then not irritate your input.

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.




回答3:


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'. 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




回答4:


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().
  2. Leave spaces on either side of binary operators: while(!(a>=1&&a<=100)) is needlessly ugly and hard to read.
  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?
  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.



回答5:


why are you using a loop, your logic seems that it must have a if ---else condition

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;
    }
}


来源:https://stackoverflow.com/questions/18525400/infinite-loop-code-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!