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 char
s (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 char
s in the string with strlen
.
numbers
is misleading here though. It'll accept any non whitespace char
s.
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);
}
}