fscanf with optional fields, spaces?
I'm trying to read a file into and create a single long string based on the contents of the file. However, it has to accommodate for different amounts of spaces, commas, quotes, and end of lines.
Input file input.txt:
,abc hi
"def hi(1)"
ghi bye bye(3)
jkl hello,
mno cat, "pqr dog mouse(4)", stu bird snake
vwx
fish
Output Final string
"abc hi, def hi(1), ghi bye bye(3), jkl hello, mno cat, pqr dog mouse(4), stu bird snake, vwx fish"
Here's what I've tried:
char string[40];
char string2[40];
char junk[20];
char junk2[20];
int count = 0;
char strFinal[200];
FILE *fin;
fin = fopen("input.txt", "r");
if (!fin)
return -1;
while (fscanf(fin, "%[^, ()\t]%[, \t]%[^, \t]%[, \t]", &string, &junk, &string2, &junk2))
{
if (count++ > 1)
{
strcat(strFinal, ", ");
}
strcat(strFinal, string);
strcat(strFinal, " ");
strcat(strFinal, string2);
}
...
// strip " from strFinal, print final string
Last edited by phyx; 01-16-2007 at 05:18 PM.
|