I am trying to read two numbers from a text file. I used strtok
, and the delimiter is " "
. The text file (named data.txt) file has only two numbers, the line is "3 5"
. But the program crashes... any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE *data;
data = fopen("data.txt", "r");
int m, n;
char *line, *number;
while(!feof(data))
{
fscanf(data, "%s", line);
number = strtok(line, " ");
m = atoi(number);
number = strtok(NULL, " ");
n = atoi(number);
}
}
line
is a uninitialized pointer, it doesn't point to any valid memory location so you can't use it to store data, use an array instead.while(!feof(data))
is not what you'd want to use to control your read cycle.Use
fgets
/sscanf
to parse the values, simple and easy way to do it:Or as @chux pointed out, to detect extra junk on the line:
If the values in the file can be outside the range of an
int
consider usingstrtol
instead ofsscanf
.