8

I've been using fprintf for a while now and I'd like to ask a question. What is the equivalent of this fprintf line:

fprintf(OutputFile, "%s", "SomeStringValue");

using ofstream ?

How to use the "%s" in ofstream is what I'd really like to know. How to take the next argument and print it as a string?

aresz
  • 2,589
  • 6
  • 34
  • 51
  • Something like `os << "SomeStringValue";`, where `os` is a properly opened [`std::ofstream`](http://en.cppreference.com/w/cpp/io/basic_ofstream). – WhozCraig Aug 15 '13 at 23:19
  • this really has nothing to do with `string`'s consider removing that tag. – UpAndAdam Aug 15 '13 at 23:22
  • 1
    When you really need to fall back on non-trivial printf-style strings, you can use `snprintf` to build the string, and then output it on your stream. – paddy Aug 15 '13 at 23:33
  • 1
    Actually, you should use `fprintf(OutputFile, "SomeStringValue");` instead of your approach when the entire format string is `"%s"` or, better, yet, `fputs("SomeStringValue", OuputFile);` as this avoid parsing the string for format specifiers. – Dietmar Kühl Aug 15 '13 at 23:39
  • @DietmarKühl: Is mixing C style `FILE` streams and C++ I/O streams guaranteed to provide consistent output? – jxh Aug 16 '13 at 00:54
  • @DietmarKühl: Never mind, you already answered my question with [this answer](http://stackoverflow.com/a/9654191/315052). – jxh Aug 16 '13 at 01:05
  • @jhx: By default you can read and write alternatingly from/to the standard streams using iostreams or stdio. The net effect is that iostreams is quite slow on the standard streams. Call `std::sync_with_stdio(false)` to disable the synchronization and make iostreams a lot faster. – Dietmar Kühl Aug 16 '13 at 07:29

2 Answers2

3

You don't use it.

The equivalent is essentially:

std::ofstream x("your_file");
x << "SomeStringValue";
x.close();

Go read about it on any of several reference pages. Such as http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/

UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
3

You can't. You just write the string to the stream.

If you mean you want to provide some additional formatting to the string (like right justified with space padding), then you can use the I/O manipulators setfill(' ') (set the fill character to be the space character) and setw(length) (setting the width of the output). If you want something that mimics the syntax of the C style format strings, you can use Boost.format.

std::cout << boost::format("%s") % "SomeStringValue";
jxh
  • 69,070
  • 8
  • 110
  • 193