Trying to figure out how to read in multiple variables through a file. for example i know how to read in one, if i have a file called "datainput" which has the line of text "150" and then in my program if I have int value; and then scanf("%d", &value); when i run the program with the file it reads the file and then applies it to my variable. but what I am trying to do now is something similar but instead read in 2 values, so say in my text file i will have "3.1, 3.4" something like this and then put it on variable 1 and 2 something like that. anyone have any ideas?
2 Answers
To read in two values all you have to do is add an additional format specifier to the scanf() call:
scanf("%d %d", &value1, &value2); //reads two values
Also, just to note if you are reading from a file you need to use the function fscanf has a similar format to scanf except that you need pass a pointer to the file you are working with:
char inFileName[] = "input.txt";
FILE *inFile;
/* open the input file */
inFile = fopen(inFileName, "r");
fscanf(inFile, "%d %d", &value1, &value2); //reads two values from FILE inFile
3 Comments
value1, value2, then your scanf would be scanf("%d, %d", &value1, &value2);fscanf(), I was getting to that partIf your format is:
3.1, 3.4
Try:
float float1, float2;
int num_things_read = scanf("%f, %f",&float1,&float2);
The scanf() man page has a full listing of all the formats you can use. The format string can be used to specify the format of the input much like printf() can be used to specify the format of the output (although not exactly the same).
There's also a short series of examples here.
As a commenter points out, if you're reading from a file, you'll need to use fscanf():
int num_things_read = fscanf(stream, "%f, %f",&float1, &float2);
Where stream is something you've previously opened with fopen(), such as a file.
6 Comments
"%f, %f", but your input is "1.2, 1.5", both values are read.