Reputation: 89
I want to be able to make a loop that reads line by line, then captures the digits in the beginning of each line into an int array, and the characters in a 2d character array. I thought I could have a loops like,
while (fscanf(file, "%d %c %c %c", &num, &f, &e, &h)==4){}
but that is if C could read strings. How can I read each line?
Upvotes: 2
Views: 707
Reputation: 2420
#include <stdio.h>
#include <stdlib.h>
int main()
{
char matrix[500][500], space;
int numbers[500], i = 0, j;
FILE *fp = fopen("input.txt", "r");
while(!feof(fp))
{
fscanf(fp, "%d", &numbers[i]); // getting the number at the beggining
fscanf(fp, "%c", &space); // getting the empty space after the number
fgets(matrix[i++], 500, fp); //getting the string after a number and incrementing the counter
}
for(j = 0; j < i; j++)
printf("%d %s\n", numbers[j], matrix[j]);
}
variable 'i' is counting how many lines you have. If you have more than 500 lines you can change that value or then use a dynamic vector.
Upvotes: 0
Reputation: 3009
what about this:
char buf[512];
int length = 0;
while(fgets(&buf[0], sizeof(buf), stdin)) {
length = strlen(&buf[0]);
if(buf[length-1] == '\n')
break
/* ...
...
realloc or copy the data inside buffer elsewhere.
...*/
}
/* ... */
Upvotes: 0
Reputation: 172458
For reading a line you can use :-
while ( fgets ( line, sizeof line, file ) != NULL )
or you can try
while ((read = getline(&line, &len, fp)) != -1)
Upvotes: 1