Reputation: 5690
Below is a fairly simple C program to open a text file (input.txt), read the first four lines, commit them to an array, and print the first item in the array (i.e. the first item in the text file)
The problem is, it prints nothing. There are no compile errors and the program just exits without any output. Where am I going wrong?
#include <stdio.h>
int main()
{
FILE * custom_calib = fopen("input.txt", "r");
float custom_calib_contents[4];
int i;
for(i = 0; i < 4; i++)
{
fscanf(custom_calib, "%f", &custom_calib_contents[i]);
}
double X_scale = custom_calib_contents[0];
double X_intercept = custom_calib_contents[1];
double Y_scale = custom_calib_contents[2];
double Y_intercept = custom_calib_contents[3];
char word [80];
sprintf(word, "%f", X_scale);
return 0;
}
Upvotes: 0
Views: 790
Reputation: 20609
Your code does not check for error conditions, which is always important. (How do you know the file was opened correctly otherwise?)
The real issue, though, is that you used sprintf
instead of printf
to output the string. sprintf
will put your output into a C-string (that's what the s
means). printf
will print the output to the screen.
Upvotes: 3
Reputation: 35983
use printf
instead of sprintf
.
printf
prints something to the screen, while sprintf
fills an array of characters (i.e. in essence a string) with something.
Note, that while sprintf
accepts as first argument the char array it shall write to, printf
does not requires this first argument since it outputs it onto the screen.
Upvotes: 2