Denys_newbie
Denys_newbie

Reputation: 1160

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

First fprintf() works as it has to work, but second output whole nonsense enter image description here

#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
}

Upvotes: 1

Views: 440

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35455

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);

Upvotes: 4

Related Questions