3

I am having an issue with printing a string which im using for debug purposes.

I create the string like so:

//checker is int 
std::stringstream buttonx; 
buttonx << "Button" << checker << "_x";

Now i try to print it to my error.txt file


FILE * p;
p = fopen ("error.txt","w");
fprintf(p, "%s" , buttonx.str());
fclose(p);

The output is:

,æ0

Its different every time. I'm not sure whats going on was hopeing some could explain the mistake?

2 Answers 2

7

fopen is plain C and cannot handle std::string. You need to input a char*, which you can access by calling .c_str() on the string, like this:

fprintf(p, "%s", buttonx.str().c_str());
Sign up to request clarification or add additional context in comments.

3 Comments

Or, use a std::ofstream as the C++ gods intended.
How would std::ofstream syntax look ?
@Dave: std::ofstream f("error.txt"); f << buttonx.str();. Or, if you're not writing anything else to the file, even std::ofstream("error.txt") << buttonx.str(); might work.
0

the function fprintf wants a null terminated string (a C string); you need the c_str() instead of yours:

 buttonx.c_str()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.