简体   繁体   中英

C - using sprintf

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 (ie 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;
}

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.

use printf instead of sprintf .

printf prints something to the screen, while sprintf fills an array of characters (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM