0

i'm making a program in C. that keeps track of items in a warehouse.

and i want to force the user to include at least one number! example dvd1, dvd2. hello1, hello20

is there a way to do this? at this moment i am using scanf.

and i want the product code to have the requirement format of xx-xxx-xxx were x are numbers.

i'm using scanf ( %[0-9-]s

Mvh Anton!

Nhailum
  • 3
  • 1

2 Answers2

1

scanf doesn't work like that, it doesn't have in-depth validation.

You need to read the input into a char array, then loop through each character and see if it is a digit.

Something like this (untested):

char buffer[1000];
int i = 0, hasDigit = 0;

scanf("%s", buffer);
while (i < sizeof(buffer) && buffer[i] != 0 && !hasDigit)
{
  hasDigit = isdigit(buffer[i]);
  i++;
}

// if hasDigit is 0, there are no digits

Note: scanf isn't great, since if you enter more characters than fit in the buffer it can cause a buffer overflow. It is better to use fgets(buffer, sizeof(buffer), stdin);

Daniel
  • 4,797
  • 2
  • 23
  • 30
0

Read the input and you can iterate through as in This SO question. You can check to see if chars match the input you want pretty easily from that point on.

Community
  • 1
  • 1
Benjamin Trent
  • 7,378
  • 3
  • 31
  • 41