I am reading set of numbers from file by fscanf(), for each number I want to put it into array. Problem 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
-
1Please provide some sample input and explain how you would like it to be parsed and what the result should be. – Paul R Mar 30 '11 at 16:18
-
1Just add a `,` in the fscanf format string, as I did in my answer. E.g. use `"%f,"` instead of `"%f"`. You many need to use a separate format string for the last number of each line to avoid having to terminate lines with a `,` – thkala Mar 30 '11 at 16:27
-
It works for me without separate format for last number of each line, just separated by comma and using "%f," great, thanks a lot – Waypoint Mar 30 '11 at 16:33
4 Answers
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?

- 84,049
- 23
- 157
- 201
-
Thanks, I have tried it, but no success. I am filling the internal matrix for some computing - see my Edit – Waypoint Mar 30 '11 at 16:26
-
I tried this on a ProjectEuler question (i.e. different input). Surprisingly, even if the last character per line is not a comma, this still seems to work. – ComputerScientist Dec 29 '16 at 04:56
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.

- 476,176
- 80
- 629
- 1,111
-
+1 for awesome code although since it looks like he's starting out this might not help much except for being able to copy it. – Jesus Ramos Mar 30 '11 at 16:54
Jerry Coffin's answer is nice, though there are a couple of caveats to watch for:
fscanf returns a (negative) value at the end of the file, so the loop won't terminate properly.
i
is incremented even when nothing was read, so it will end up pointing one past the end of the data.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 , "
.

- 4,413
- 4
- 38
- 48
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)