简体   繁体   中英

How to read only 4 digits in C

I want to get input from the user 1234 and when i press in the 4 digit to finish the scanf I tried

    int num = 0;
    scanf("%4d",&num);
    getchar()
    printf("%d",num);

but it stopped only when I press enter and get the 4 first numbers, I don't want to press on enter I want to finish the input on the 4 digit and to get the number in num. also is it possible to get the 4 numbers to 4 different variables

   int num = 0;
   int num2 = 0;
   int num3 = 0;
   int num4 = 0;
   scanf("%d%d%d%D",&num,&num2,&num3,&num4);
   getchar()

but it didn't work also I can change the function of scanf to something else

It is not possible in standard C. You have to press enter. Basically, terminals used when C was created very often were sending data to the computer when the internal buffer was full or enter pressed.

If you are happy to press enter after numbers are entered then:

int toNumber(char c)
{
    int result = 0;
    if(isdigit((unsigned char)c))
    {
        result = c - '0';
    }
    return result;
}

int isValid(const char *restrict str)
{
    int result = 0;
    if(strlen(str) == 4)
    {
        result = 1;
        while(*str)
        {
            if(!isdigit(*str++))
            {
                result = 0;
                break;
            }
        }
    }
    return result;
}

char *removeLastLF(char *str)
{
    char *wrk = str;
    if(str && *str)
    {
        while(*(str + 1)) str++;
        if(*str == '\n') *str = 0;
    }
    return wrk;
}

int main(void)
{
    char num[5];
    int var1, var2, var3, var4;

    fgets(num, 5, stdin);
    if(!isValid(removeLastLF(num))) printf("Wring format\n");
    else
    {
        var1 = toNumber(num[0]);
        var2 = toNumber(num[1]);
        var3 = toNumber(num[2]);
        var4 = toNumber(num[3]);
    }
}

Input does not work like this. Your "standard input library" is buffered , it means it uses buffer, which holds characters. Pressing enter triggers that buffer to flush data and then you can read it from your program.

You need unbuffered input, AFAIK, it is not easy-portable, so there is no standard solution .

So you have 2 options:

  1. Press enter after entering the number, then you deal with input just like with a regular sequence of characters.
  2. Or use library for unbuffered input.

For the second option there was a library called conio.h (it is pretty old), which implemented getch() method for unbuffered input, it is also implemented in ncursess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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