Reading from a file, atoi() returns zero only on first element
Posted
by Nazgulled
on Stack Overflow
See other posts from Stack Overflow
or by Nazgulled
Published on 2010-04-07T16:40:52Z
Indexed on
2010/04/07
16:43 UTC
Read the original article
Hit count: 406
Hi,
I don't understand why atoi()
is working for every entry but the first one. I have the following code to parse a simple .csv file:
void ioReadSampleDataUsers(SocialNetwork *social, char *file) {
FILE *fp = fopen(file, "r");
if(!fp) {
perror("fopen");
exit(EXIT_FAILURE);
}
char line[BUFSIZ], *word, *buffer, name[30], address[35];
int ssn = 0, arg;
while(fgets(line, BUFSIZ, fp)) {
line[strlen(line) - 2] = '\0';
buffer = line;
arg = 1;
do {
word = strsep(&buffer, ";");
if(word) {
switch(arg) {
case 1:
printf("[%s] - (%d)\n", word, atoi(word));
ssn = atoi(word);
break;
case 2:
strcpy(name, word);
break;
case 3:
strcpy(address, word);
break;
}
arg++;
}
} while(word);
userInsert(social, name, address, ssn);
}
fclose(fp);
}
And the .csv sample file is this:
900011000;Jon Yang;3761 N. 14th St
900011001;Eugene Huang;2243 W St.
900011002;Ruben Torres;5844 Linden Land
900011003;Christy Zhu;1825 Village Pl.
900011004;Elizabeth Johnson;7553 Harness Circle
But this is the output:
[900011000] - (0)
[900011001] - (900011001)
[900011002] - (900011002)
[900011003] - (900011003)
[900011004] - (900011004)
What am I doing wrong?
© Stack Overflow or respective owner