2

I tried with below code:

String hi = "hi";
String bye = "bye";
fprintf(fileout, "%d: %s, %s", 10, hi, bye); //fail 
fprintf(fileout, "%d: %s, %s", 10, "hi", "bye");//ok

however, this cannot write hi bye to the text file. What is wrong?

0

2 Answers 2

5

fprintf and related functions are C functions.

You need a "C string", which is a null-terminated character array (char * or char const *), not a C++ string (std::string).

fprintf(fileout, "%d: %s, %s", 10, hi.c_str(), bye.c_str());

See fprintf and c_str().

Though C++ code will typically use the C++ I/O functions.

Sign up to request clarification or add additional context in comments.

2 Comments

Though, do note that the String that manhon is using is likely not std::string. Note that the capitalization differs. manhon, check whether your String class has a member function similar to std::string::c_str() and try using that.
Yes, @c45207 makes a good point. Look for a function that returns char * (or const char * or char const *).
0

You don't normally want to use fprintf and company in C++.

fileout << 10 << ": " << hi << ", " << bye;

2 Comments

I use fprintf becoz i am trying to write float numbers to file, some are round up to digit, some are round up to 2 decimal.
@manhon: Then you'll want to look up std::setw and std::setprecision.

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.