4
I have a text file (txt) that contains the following values:
12 90
These two values I keep and my variables a
and b
, that is to say a
is equal 12
and b
is equal 90
, and I’m using the function scanf()
to receive these values from the file as follows:
#include <stdio.h>
int main()
{
int a, b;
scanf("%d %d", &a, &b);
printf("Valor a = %d, b = %d", a, b);
return(0);
}
Exit:
Value a = 12, b = 90
I run the program with the following command scanfTeste.exe < arquivo.txt
in the prompt Windows to run the program.
However, the structure of my file will change, time it will have two values or an indeterminate amount, see the examples:
- Example one of the file content:
12 90
- Example two of file content:
12 90 33 77
Whereas the values are separated by spaces to facilitate the reading of the data.
My doubt:
As you can see the amount of parameters you pass to scanf("%d %d ...", &a, &b, ...)
changes depending on the amount of values in the file row, as I can make the function scanf()
receive a number of parameters according to the amount of values in the file line?
Do you know the number of elements or not? If you do not know, the solution you are asking for does not work.
– Maniero
Yes, one of the values indicates the amount of elements in the file, and the first value and then the values.
– gato
I think using a loop that reads a value at a time will be easier and simpler than trying to make a smart scan.
– hugomg
@hugomg yes I implemented in a loop with fscanf and it worked.
– gato
The description of your question was very good! :)
– Sérgio Mucciaccia