Can any one explain to me how to make a C program to read input from a file according to the following scenario:
12
2-4,7,9;
1,4,11-12;
1,4,10,12;
1,4-8,10-12;
1,8;
1,3-6,8,10-12;
1,3,5-6,8,11;
1,8,10-12;
1-8;
;
2;
2-4,7-10,12;
The first number (on the first line) describes what size the grid should be, in this case a 12x12 grid. The following lines describe how many cells are occupied on each row of the grid. For example, in the first row the cells from 2 to 4 and 7 and 9 are occupied; in the second row, the cells 1, 4 and from 11 to 12 are occupied and so on.
Right now I have this code, but it is not solving my problem ...
#include <stdio.h>
#include <stdlib.h>
void main()
{
char content[3000];
int value;
FILE *ptr_file = fopen("data.txt", "r");
if(!ptr_file)
return 1;
int j;
while(fgets(content, 3000, ptr_file)!=NULL){
printf("%s", content);
value = atoi(content);
for(j=0; j<3000; j++){
value = content[j];
printf("%i", value);
}
}
return 0;
}
Console throws just a bunch of random numbers ...
void main(). Useint main(void)orint main(int argc, char *argv[])instead (especially when you writereturn 0;at the end).atoion the entirecontentbuffer.atoionly converts a single string to an integer. You need to use something likesscanforstrtokto parse the buffer into individual string tokens.strtok()obliterates the delimiter, so you can't really use that.strtol()tells you where it stopped scanning — it looks like a good candidate for this. It's what I use in my library functions that parse ranges of numbers like the ones shown.