开发者

fscanf in C - how to determine comma?

I am reading set of numbers from file by fscanf(), for each number I want to put it into array. Proble开发者_StackOverflow中文版m is that thoose numbers are separated by "," how to determine that fscanf should read several ciphers and when it find "," in file, it would save it as a whole number? Thanks


This could be a start:

#include <stdio.h>

int main() {
    int i = 0;

    FILE *fin = fopen("test.txt", "r");

    while (fscanf(fin, "%i,", &i) > 0)
        printf("%i\n", i);

    fclose(fin);

    return 0;
}

With this input file:

1,2,3,4,5,6,
7,8,9,10,11,12,13,

...the output is this:

1
2
3
4
5
6
7
8
9
10
11
12
13

What exactly do you want to do?


I'd probably use something like:

while (fscanf(file, "%d%*[, \t\n]", &numbers[i++]))
    ;

The %d converts a number, and the "%*[, \t\n]" reads (but does not assign) any consecutive run of separators -- which I've defined as commas, spaces, tabs, newlines, though that's fairly trivial to change to whatever you see fit.


fscanf(file, "%d,%d,%d,%d", &n1, &n2, &n3, &n4); but won't work if there are spaces between numbers. This answer shows how to do it (since there aren't library functions for this)


Jerry Coffin's answer is nice, though there are a couple of caveats to watch for:

  1. fscanf returns a (negative) value at the end of the file, so the loop won't terminate properly.

  2. i is incremented even when nothing was read, so it will end up pointing one past the end of the data.

  3. Also, fscanf skips all whitespace (including \t and \n if you leave a space between format parameters.

I'd go for something like this.

int numbers[5000];
int i=0;
while (fscanf(file, "%d %*[,] ", &numbers[i])>0 && i<sizeof(numbers))
{
    i++;
}
printf("%d numbers were read.\n", i);

Or if you want to enforce there being a comma between the numbers you can replace the format string with "%d , ".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜