Page 1 of 1

Regarding input

Posted: Sun Mar 19, 2006 10:05 pm
by rafagiu
Hello, everyone.

What's the best way to read an input file where the test cases are separeted by line breaks or blank lines, instead of having an explicit counter?

Example:

Code: Select all

this is test case one
this is test case two
Instead of

Code: Select all

2

5 this is test case one
5 this is test case two
The second case has an explicits the number of test cases (2) and each test case explicits the number of input elements (5 and 5).

For the first case, I have been reading the input with fgets into a string and processing its elements with sscanf, but it's quite boring and very little elegant this way. Can anybody share a better alternative?

Thanks in advance![/code]

Re: Regarding input

Posted: Sat May 20, 2006 8:45 pm
by Martin Macko
Try to use %[...] scanf conversions. For instance, to parse the input

Code: Select all

aaaa      bbbbb cc
      
   ddddd      
eeeee    ffff   
you can write something like
code wrote:#include <stdio.h>

int main(void)
{
........int l=0;
........char s[1000];

........while (!feof(stdin))
........{
................printf("line %d:", ++l);
................while (scanf("%[^ \n]%*[ ]", s)>0) printf(" '%s'", s);
................printf("\n");
................scanf("%*c%*[ ]");
........}

........return 0;
}
The output of the program to the given input is

Code: Select all

line 1: 'aaaa' 'bbbbb' 'cc'
line 2:
line 3: 'ddddd'
line 4: 'eeeee' 'ffff'
For more information on %[...] try man scanf.

Posted: Sun May 21, 2006 5:20 am
by chunyi81
Use gets or fgets function. If length of line read in is > 0, then parse using strtok function.