Regarding input

Write here if you have problems with your C source code

Moderator: Board moderators

Post Reply
User avatar
rafagiu
New poster
Posts: 12
Joined: Sat Sep 24, 2005 8:30 pm

Regarding input

Post by rafagiu » Sun Mar 19, 2006 10:05 pm

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]

User avatar
Martin Macko
A great helper
Posts: 481
Joined: Sun Jun 19, 2005 1:18 am
Location: European Union (Slovak Republic)

Re: Regarding input

Post by Martin Macko » Sat May 20, 2006 8:45 pm

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.
Last edited by Martin Macko on Mon Jun 12, 2006 3:30 am, edited 1 time in total.

chunyi81
A great helper
Posts: 293
Joined: Sat Jun 21, 2003 4:19 am
Location: Singapore

Post by chunyi81 » Sun May 21, 2006 5:20 am

Use gets or fgets function. If length of line read in is > 0, then parse using strtok function.

Post Reply

Return to “C”