C++, regarding fprintf and ofstream

2019-05-03 12:20发布

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?

2条回答
爷的心禁止访问
2楼-- · 2019-05-03 12:37

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";
查看更多
We Are One
3楼-- · 2019-05-03 12:38

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/

查看更多
登录 后发表回答