Tuesday, 17 September 2013

(Reading CSV file) scanf skip to next line of input after pattern mismatch

(Reading CSV file) scanf skip to next line of input after pattern mismatch

I want to give an error message if scanf encounters a mismatch and then
continue reading the rest of the inputs. My current code goes into an
infinite loop if one of the inputs isn't formatted correctly.
Expected input:
101,Betty,Hay,123 Main St.,23
234,Sheila,Benn,937 Ash Ave.,46
384,Ron,Jewell,3991 Cedar Ave.,30
291,Bill,Read,83 Crescent St.,19
103,Alexander,Ott,100 2nd St.,21
115,Tricia,Munson,585 Oxen Ave.,28
118,Sam,Munson,585 Oxen Ave.,35
110,Valerie,Parker,1513 Copper Rd.,37
Code:
#include <stdio.h>
int main()
{
int sum = 0;
int count = 0;
while (1)
{
int id;
char first[80], last[80], addr[80];
int age;
scanf("%d,%80[^,],%80[^,],%80[^,],%d", &id, first, last, addr, &age);
if (feof(stdin)) break;
printf("id=%d first=%s last=%s addr=%s age=%d\n",
id, first, last, addr, age);
sum += age;
count++;
}
printf("Average age is %f\n", (float)sum / count);
return 0;
}
I tried to fix this by putting scanf inside an if statement comparing it
to the expected number of reads, this worked for displaying the error
message but doesn't help reading the rest of the input. Is there a way to
skip to the next line of input?

No comments:

Post a Comment