This is another method in which you may or may not want to use:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 10
struct address {
int street_number;
char* street_name;
char* suburb_name;
int postcode;
};
struct address addbook[MAX];
int main(int argc, char** argv)
{
char* result = NULL;
char buf[BUFSIZ];
char *delims = " \n\t";
int input = 1;
int i = 0;
if (fgets(buf,BUFSIZ,stdin) == NULL)
{
fprintf(stderr,"Error getting info\n");
exit(1);
}
/* Else process the data */
result = strtok(buf,delims);
while (result != NULL && input <= 4)
{
/* read into different parts of the array depending on input */
if (input == 1) {
addbook[i].street_number = atoi(result);
} else if (input == 2) {
addbook[i].street_name = malloc(strlen(result) + 1);
if (addbook[i].street_name == NULL)
{
fprintf(stderr,"Could not allocate mem!");
exit(1);
}
addbook[i].street_name = result;
} else if (input == 3) {
addbook[i].suburb_name = malloc(strlen(result) + 1);
if (addbook[i].suburb_name == NULL)
{
fprintf(stderr,"Could not allocate mem!");
exit(1);
}
addbook[i].suburb_name = result;
} else if (input == 4) {
addbook[i].postcode = atoi(result);
}
input++;
result = strtok(NULL,delims);
}
/* Print out the structure to test if it works */
printf("Street Number: %d\n",addbook[i].street_number);
printf("Street Name: %s\n",addbook[i].street_name);
printf("Suburb Name: %s\n",addbook[i].suburb_name);
printf("Postcode: %d\n",addbook[i].postcode);
return 0;
}
Its still a bit messy but it may help you get an idea of what you want to do. Basically I used strtok() to break up the string read in by fgets(). Then individual tokens are placed into different parts of the structure depending on the "input" variable. Also I changed some of your structure details - instead of having a MAX on all the individual structure members I simply just made an array of structures of max size MAX.
The code above only shows input for the first index of the "addbook" structure. You will need to reset both the "input" and "i" variables if you wish to read into the second index. Also, you need to tweak some of the code (obviously) to how you want it done.
A sample input/output:
Code:
bash-3.00# ./parse1
123 FakeSt Melbourne 3000
Street Number: 123
Street Name: FakeSt
Suburb Name: Melbourne
Postcode: 3000
As you can see I had to combine Fake St into FakeSt, you can correct this yourself if you need to. You may also want to use a switch statement since you will have lots of if statements otherwise - the choice is yours.