1

I need to read in separate numbers from a file and then use them in code.

For example the file will say things like

2 5
8 9
22 4
1 12

And right now I have:

while(fgets(line, MAX_LEN, in) != NULL)  
{
    ListRef test = newList();
    token = strtok(line, " \n");
    int x = token[0] - '0';
    int y = token[2] - '0';
}

Which works fine, except not if one or both of the numbers is multiple digits. How would I change this to read in both numbers (there will always be two, and that's it) on a line, regardless of their length?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

2 Answers2

1
while (fgets(line, sizeof(line), in) != NULL)  
{
    int x, y;
    if (sscanf(line, "%d %d", &x, &y) != 2)
        ...report format error...
    ...use x and y as appropriate...
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

Given a line of numbers in line (as in your while loop), you can do it like this:

char *p;
p = strtok(line, " \n");
while (p != NULL) {
    sscanf(p, "%d", &num);
    /* do something with your num */
    p = strtok(NULL, " \n");
}

But note that strtok may have thread safety issue. See strtok function thread safety

If you just want to read all the numbers, regardless of the lines, just use fscanf:

while (fscanf(in, "%d", &num) == 1) {
    /* do something with your num */
}
Community
  • 1
  • 1
Xiao Jia
  • 4,169
  • 2
  • 29
  • 47