Home > OS >  C- How to restrict user to only enter a specific amount of elements?
C- How to restrict user to only enter a specific amount of elements?

Time:09-25

I want the user to enter 10 numbers, and if they enter anything else but 10 numbers I want to tell them it's invalid. Not quite sure how to do it, I tried with an if-statement like this:


{
    char numbers[11];
    printf("Enter your 10 numbers: ");
    scanf("%s", numbers);

    if ( *numbers != 11)
        printf("Enter a valid number.\n");
    else
        printf("Your number is %s: \n", numbers);

    return 0;
}

Is there a way to do this?

CodePudding user response:

You should restrict the read string to max 10 chars (with s) - or else you risk writing out of bounds. You should also make sure that reading works and you can count the number of chars in the string with strlen.

numbers is misleading here though. It'll accept any non whitespace chars.

Example:

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

int main()
{
    char numbers[11];
    printf("Enter your 10 numbers: ");
    if(scanf("s", numbers) != 1 || strlen(numbers) != 10) {
        printf("Enter a valid number.\n");
    } else {
        printf("Your number is: %s\n", numbers);
    }
}

If you want to make sure that the entered string only contains digits, you could restrict the scanf format to [0-9]:

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

int main()
{
    char numbers[11];
    printf("Enter your 10 digits: ");
    if(scanf("[0-9]", numbers) != 1 || strlen(numbers) != 10 ) {
        printf("Enter a valid number.\n");
    } else {
        printf("Your number is: %s\n", numbers);
    }
}
  • Related