简体   繁体   中英

Why fprintf() function in my code don't working properly?

First fprintf() works as it has to work, but second output whole nonsense在此处输入图像描述

#include <string>

int main()
{
    FILE* f;
    fopen_s(&f, "text.txt", "w");
    std::string name = "hello";
    int area = 123;
    char ch = 'i';

    fprintf(f, "abc"); // OK

    fprintf(f, "|%-12s |%-5c |%-9d |", name.c_str(), area, ch); // not OK
}

The %s format specifier expects a null-terminated array of char , not std::string . Thus the fprintf 's behavior is undefined.

Use:

fprintf(f, "|%-12s |%-5c |%-9d |", name.c_str(), area, ch);

as the c_str() function returns the null-terminated array.


In addition, the format strings for the other types also seem incorrect. To print an int , the format specifier is %d , not %c , and the format specify for char is %c , not %d .

Thus the final call to fprintf should be:

fprintf(f, "|%-12s |%-5d |%-9c |", name.c_str(), area, ch);

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