AKidNamedCoder
AKidNamedCoder

Reputation: 3

How to allow only digits to be entered in an array?

So I am trying to write a program that receives a 10 digit phone number from the user. It must only be 10 characters long. It can only consist of digits. Entering a alphabet character or special character will give an error message. I have tried using the isdigits() function but that doesn't seem to work. Here is my code so far.

Is there any other way to do this without using isdigits()?

#include <stdio.h>
#include <string.h>
#include <ctype.h>
void clearKeyboard(void);

int main (void)
{
    char phoneNum[11];
    int needInput = 1;
    int i;
    int flagBad = 0;
    while (needInput == 1) {
        scanf_s("%10s", phoneNum);
        clearKeyboard();
        // (String Length Function: validate entry of 10 characters)
        if (strlen(phoneNum) == 10) {
            needInput = 0;
            for (i = 0; i < 10; i++) {
                if (isdigits(phoneNum[i] == 0)) {
                    flagBad = 1;
                }
            }
            if (flagBad == 1) {
                needInput = 1;
                printf("Enter a 10-digit phone number: ");
            }
        }
        else needInput == 0;    
    }
    printf("Successful");
    return 0;
}

void clearKeyboard(void)
{
    while (getchar() != '\n'); // empty execution code block on purpose
}

Upvotes: 0

Views: 157

Answers (4)

chux
chux

Reputation: 153508

scanf_s("%10s", phoneNum); fails as it is missing an argument. Review your scanf_s() documentation.


I do not recommend scanf_s(). Instead avoid mixing user I/O with input validation. Get the input, then validate it.

   char buf[80]; // Be generous.
   if (fgets(buf, sizeof buf, stdin)) {
     buf[strcspn(buf, "\n")] = '\0'; // Lop off potential \n
     // OK we have the input, now validate.

     char phoneNum[11];
     int n = 0;
     // Use sscanf, isdigit, or ...
     if (sscanf(buf, "%10[0-9]", phoneNum, &n) == 1 && n == 10 && buf[n]==0) {
       puts("Success");
     } else {
       printf("Bad input <%s>\n", buf);
     }

"%10[0-9]%n", phoneNum, &n --> Scan 1 to 10 digits into phoneNum[] and append a '\0'. Save scanning offset into n

Upvotes: 1

hess
hess

Reputation: 96

As AbdelAziz stated, you should use is isdigit(), not isdigits(). Also, your if statement is wrong:

if (isdigits(phoneNum[i] == 0))

should be:

if (isdigit(phoneNum[i]) == 0)

Upvotes: 0

Cm Jagtap
Cm Jagtap

Reputation: 177

You should use scanf("%10s", phoneNum); and also include #include <stdlib.h> which contains isdigit() method.

Upvotes: 0

AbdelAziz AbdelLatef
AbdelAziz AbdelLatef

Reputation: 3744

I think the function you need is isdigit(), not isdigits().

Upvotes: 0

Related Questions