|
For the 4240 project in C, the spec does
not say that you HAVE to validate the address format, but you may
do so. Doing so will make your program better, as less errors may
be entered by the user. A valid address is one which has four sections
each ending with a semicolon.
An example of a valid address - 1 High Street;Some Place;Some Where;Here;
An example of an invalid address - 1 High Street;No Place;No Where;Not
Here
All
we need to do to check the address is to loop through the entered
address counting the semicolon characters. This can be implemented
as follows -
1
#include <stdio.h>
2 #include <stdlib.h>
3
4 int main (void)
5 {
6
char
address[] = "Address;With;Semi;Colons;"; /*--
A valid address --*/
7
char
*p;
/*-- A pointer to a char --*/
8
int
count=0; /*--
A counter for the semicolons --*/
9
10
/*-- Loop through address until we hit the null --*/
11
/*-- Count how many ; chars we have in the address --*/
12
for
(p=address; *p; p++)
13
if
(*p == ';')
14
count++;
15
16
if (count
== 4)
17
printf("Address
is valid\r\n");
18
else
19
printf("Address
is invalid\r\n");
20
21 return
EXIT_SUCCESS;
22 }
Lines
1 and 2 include the required header files.
Line 4 is the start of the main function (returning an int, taking
no arguments).
Line 6 declares and initializes our address variable (the address
we shall check).
Line 7 declares a pointer to a char variable (this is used to step
through the address).
Line 8 declares and initializes our semicolon counter variable count
to zero.
Line 12 is where we set up our loop as follows -
initialize) p=address
- set our char pointer to point to the first char of the address.
loop until) *p -
loop while we are not at the end of the address (*p != '\0').
increment) p++ -
set our char pointer to point to the next character in the address.
Line 13 checks to see if the current char is a semi colon.
Line 14 increments the semi colon counter, if the current character
is a semicolon.
Line 16 checks the count variable is equal to 4.
Line 17 prints a message that the address is valid, if count is
equal to 4.
Line 19 prints a message that the address was invalid, if count
does not equal 4.
Line 21 return exit success back to the operating system.
The
one thing the above code is missing is a check to ensure that the
address contained data. As ";;;;" would be a valid address
if validated by the above. Now that is incorrect as an address needs
4 sections separated by 4 semicolons not 4 semicolons alone. I will
not give you the code to fix that slight bug (intentional), but
what you need to do is check that the address length is greater
than 4 (a simple check). You could do more advanced address checking
but as far as this little bit of help goes that's all folks ...
but I hope it helped you a little.
Back Home
|