I am able to extract fields in comma separate format using sscanf (see below) if all fields are populated. But if a field is blank then only up to the blank field is populated. Is there any way I can carry on, ignoring problem of blank fields so that subsequent fields do get populated?
#include <stdio.h>
int main(int argc, char* argv[]) {
char* s = "Apple,Pear,Potato,11";
char fruit1[10];
char fruit2[10];
char vegetable[10];
int size;
int num = sscanf(s, "%20[^,],%20[^,],%20[^,],%d", fruit1, fruit2, vegetable, &size);
if (num == 4) {
printf("This record contains 4 items\n");
printf("first fruit: %s, second fruit: %s, vegetable: %s, size = %d\n", fruit1, fruit2, vegetable, size);
}
else {
printf("This record does not contain 4 items\n");
}
// but here it fails - blank vegetable
char* t = "Plum,Orange,,12";
num = sscanf(t, "%20[^,],%20[^,],%20[^,],%d", fruit1, fruit2, vegetable, &size);
if (num == 4) {
printf("This record contains 4 items\n");
printf("first fruit: %s, second fruit: %s, vegetable: %s, size = %d\n", fruit1, fruit2, vegetable, size);
}
else {
printf("This record does not contain 4 items\n");
}
return 0;
}
/*
Prints:
This record contains 4 items
first fruit: Apple, second fruit: Pear, vegetable: Potato, size = 11
This record does not contain 4 items
*/