Nhan Tran
Nhan Tran

Reputation: 51

How to restrict users to input only text but not numbers?

I'm making a program to input book detail using struct and function.

Here is my declare using struct to manage book detail:

typedef struct {
    char name[100];
    char author[100];
    char publisher[100];
    char description[100];
    char ISBN[15];
    int quantity;
} book;

And the function to input:

void addBook(int* n, book list[1000]) {
    do {
        printf("Enter number of book you want to add: ");
        fpurge(stdin);
        scanf("%d%c", n, &enter);
        if (n == 0) break;
        if (*n < 0 || *n > 1000 || enter != '\n') printf("Invalid input, please try again.\n");
    } while (*n < 0 || *n > 1000 || enter != '\n');
    for (int i = 0; i < *n; i++) {
        printf("-----------------------------------------------------\n");
        printf("Please enter all the information of book number %d\n", i + 1);
        printf("Book title: ");
        fpurge(stdin);
        fgets(list[i].name, 100, stdin);
        printf("Book author: ");
        fpurge(stdin);
        fgets(list[i].author, 100, stdin);
        printf("Publisher: ");
        fpurge(stdin);
        fgets(list[i].publisher, 100, stdin);
        printf("ISBN: ");
        fpurge(stdin);
        fgets(list[i].ISBN, 15, stdin);
        printf("Quantity: ");
        fpurge(stdin);
        scanf("%d", &list[i].quantity);
        printf("Description (optional): ");
        fpurge(stdin);
        fgets(list[i].description, 100, stdin);
    }
}

I wonder if there is any method to restrict user to input only text for the following index:

printf("Book author: ");
fpurge(stdin);
fgets(list[i].author, 100, stdin);

If there are any numbers, inform the user to input again. I try to use do while structure for the loop but cannot think of the condition to check whether each character is number or not.

EDIT: thanks to @yLaguardia, now I know the answer. For everyone having the same question, use isdigit(variable) to check.

Upvotes: 2

Views: 124

Answers (1)

awerchniak
awerchniak

Reputation: 386

You could use the isdigit() or isalpha() functions found in ctype.h, to check. You could also directly compare the ASCII values of the user's input yourself, using this table http://www.asciitable.com/

Upvotes: 3

Related Questions