1

Hi, I am looking to be able to put some validation on the entering of my data on the 'data' entry on my structure 'packet'.

Basically it can only be 50 characters long and only have number inputs.

struct packet{ // declare structure for packet creation
    int source;
    int destination;
    int type;
    int port;
    char data[50];
};

struct packet list[50]; //Array for structure input & initiate structure 

printf("\nEnter up to 50 numeric characters of data.\n");
scanf("%s", list[x].data);

All help is useful and I thank you in advance.

jfa
  • 1,047
  • 3
  • 13
  • 39
user3103598
  • 185
  • 1
  • 1
  • 10
  • 1
    What stops you from writing such code? What exactly seems to be difficult? – PM 77-1 Dec 15 '13 at 03:47
  • I am currently studying C at university, so I am not 100% efficient with the C language. I have ideas of what I want to do but don't really know how to go about them. – user3103598 Dec 15 '13 at 04:03

3 Answers3

2

Use this:

scanf("%49s", list[x].data);

You need 49 rather than 50 because a null-terminator will be added.

Once you have your characters, use isdigit() to perform validity checking.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
2

Increase the size of your destination ot accomadate 50 char and a \0. Use a format "%50[0-9]" specifier.

struct packet{ // declare structure for packet creation
  ...
  char data[51];
};
// it can only be 50 characters long and only have number inputs
if (scanf("%50[0-9]", list[x].data) != 1) Handle_Unexpected_Input();
if (strlen(list[x].data) < 50)) String_Too_Short();

You may want a leading space to discard leading whitespace: " %50[0-9]"

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

You are looking for a way to avoid overflowing your buffer. There are many ways do do this.

Here is one example using snprintf.

Here is another example using a length-limiting format string.

To verify that all the chars (if they are encoded in ASCII) in your array are numbers, you will have to loop through each character and verify that the integer value of each char is between 48 and 57 ('0' - '9').

Community
  • 1
  • 1
karkum
  • 427
  • 4
  • 16