#include <assert.h>
#include <chrono>
#include <iomanip>
#include <iostream>
class put_printf {
static constexpr size_t failed = std::numeric_limits<size_t>::max(); // for any explicit error handling
size_t stream_size; // excluding '\0'; on error set to 0 or to "failed"
char buf_stack[2048+1]; // MAY be any size that fits on the stack (even 0), SHOULD be (just) large enough for most uses (including '\0')
std::unique_ptr<char[]> buf_heap; // only used if the output doesn't fit in buf_stack
public:
explicit put_printf(const char *format, ...)
#if __GNUC__
__attribute__ ((format (printf, 2, 3))) // most compelling reason for not using a variadic template; parameter 1 is implied "this"
#endif
{
va_list args;
va_start(args, format);
const int res = vsnprintf(buf_stack, sizeof(buf_stack), format, args);
va_end(args);
if (res < 0) { // easily provoked, e.g., with "%02147483646i\n", i.e., more than INT_MAX-1 significant characters (only observed, no guarantee seen)
stream_size = failed;
} else if (res < sizeof(buf_stack)) { // preferred path
stream_size = res;
} else { // not artificially constrained
try {
const size_t buf_size = static_cast<size_t>(res) + 1; // avoids relying on "res < INT_MAX" (only observed, no guarantee seen)
buf_heap.reset(new char[buf_size]); // observed to work even beyond INT_MAX=2^32-1 bytes
va_start(args, format);
if (vsnprintf(buf_heap.get(), buf_size, format, args) == res) stream_size = res;
else stream_size = failed; // can't happen
va_end(args);
} catch (const std::bad_alloc&) { // insufficient free heap space (or an environment-specific constraint?)
stream_size = failed;
}
}
}
friend std::ostream& operator<<(std::ostream& os, const put_printf& self) {
if (self.stream_size == failed) {
// (placeholder for any explicit error handling)
return os;
} else {
// using write() rather than operator<<() to avoid a separate scan for '\0' or unintentional truncation at any internal '\0' character
return os.write((self.buf_heap ? self.buf_heap.get() : self.buf_stack), self.stream_size);
}
}
};
class put_timestamp {
const bool basic = false;
const bool local = true;
public:
friend std::ostream& operator<<(std::ostream& os, const put_timestamp& self) {
const auto now = std::chrono::system_clock::now();
const std::time_t now_time_t = std::chrono::system_clock::to_time_t(now);
struct tm tm; if ((self.local ? localtime_r(&now_time_t, &tm) : gmtime_r(&now_time_t, &tm)) == nullptr) return os; // TODO: explicit error handling?
static_assert(4 <= sizeof(int), "");
const int microseconds = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch() % std::chrono::seconds(1)).count();
assert(0 <= microseconds && microseconds < 1000000); // TODO: (how) do we know?
// TODO: doesn't "point" in "decimal_point()" imply "dot"/"full stop"/"period", unlike an obviously neutral term like "mark"/"separator"/"sign"?
const char decimal_sign = std::use_facet<std::numpunct<char>>(os.getloc()).decimal_point() == '.' ? '.' : ','; // full stop accepted, comma preferred
// TODO: all well and good for a locale-specific decimal sign, but couldn't the locale also upset microseconds formatting by grouping digits?
os << std::put_time(&tm, self.basic ? "%Y%m%dT%H%M%S" : "%FT%T") << put_printf("%c%06i", decimal_sign, microseconds);
if (! self.local) return os << "Z";
const int tz_minutes = std::abs(static_cast<int>(tm.tm_gmtoff)) / 60;
return os << put_printf(self.basic ? "%c%02i%02i" : "%c%02i:%02i", 0 <= tm.tm_gmtoff ? '+' : '-', tz_minutes / 60, tz_minutes % 60);
}
};
int main() {
// testing decimal sign
///std::cout.imbue(std::locale("en_GB"));
///std::cout.imbue(std::locale("fr_FR"));
std::cout << put_timestamp() << " Hello, World!\n";
#if 0
typedef put_printf pf; // just to demo local abbreviation
std::cout << "1: " << pf("%02147483646i\n" , 1 ) << std::endl; // res < 0
std::cout << "2: " << pf("%02147483643i%i\n", 1, 100) << std::endl; // res < 0
std::cout << "3: " << pf("%02147483643i%i\n", 1, 10) << std::endl; // works
std::cout << "4: " << pf("%02147483646i" , 1 ) << std::endl; // works
#endif
return 0;
}
关于put_printf的注解:
// Reasons for the name "put_printf" (and not "putf" after all):
// - put_printf is self-documenting, while using the naming pattern also seen in std::put_time;
// - it is not clear whether the proposed std::putf would support exactly the same format syntax;
// - it has a niche purpose, so a longer name is not an objection, and for frequent local uses
// it is easy enough to declare an even shorter "typedef put_printf pf;" or so.
// Evaluation of delegating to vsnprintf() with intermediate buffer:
// (+) identical result without implementation and/or maintenance issues,
// (?) succeeds or fails as a whole, no output of successful prefix before point of failure
// (-) (total output size limited to INT_MAX-1)
// (-) overhead (TODO: optimal buf_stack size considering cache and VM page locality?)
// Error handling (an STL design problem?):
// - std::cout.setstate(std::ios_base::failbit) discards further std::cout output (stdout still works),
// so, to be aware of an error in business logic yet keep on trucking in diagnostics,
// should there be separate classes, or a possibility to plug in an error handler, or what?
// - should the basic or default error handling print a diagnostic message? throw an exception?
// TODO: could a function "int ostream_printf(std::ostream& os, const char *format, ...)"
// first try to write directly into os.rdbuf() before using buf_stack and buf_heap,
// and would that significantly improve performance or not?
// Hacky but idiomatic printf style syntax with c++ <<
#include <cstdlib> // for sprintf
char buf[1024]; sprintf(buf, "%d score and %d years ago", 4, 7);
cout << string(buf) <<endl;
std::ostringstream ss;
ss << format("%s => %d", "Version", Version) << std::endl;
Logger::WriteMessage(ss.str().c_str()); // write to unit test output
std::cout << ss.str() << std::endl; // write to standard output
9条答案
按热度按时间quhf5bfb1#
字段宽度
设置字段宽度非常简单。对于每个变量,只需在其前面加上“setw(n)"。如下所示:
注意“setw(n)”是如何控制字段宽度的,因此每个数字都打印在一个字段内,该字段保持相同的宽度,而不管数字本身的宽度如何。
--从"Programming/C++ tutorial" by P. Lutus开始。
jc3wubiy2#
样本输出:
代码(put_printf用法在put_timestamp中演示):
关于put_printf的注解:
hsvhsicv3#
当我同时需要cout的类型安全性和printf()简单变量的快速和简单格式时,我就像这样混合使用这两种方法,这是一个丑陋的修复,但是当我需要输出像“02/07/2014 10:05 am”这样的内容以及一些更复杂的实体时,它可以为我完成任务:
mdfafbf14#
在C++20中,你可以使用
std::format
来实现安全的printf
:除此之外,
std::format
所基于的{fmt} library还提供了print
函数,该函数将格式化和输出结合在一起:std::format
的作者。wh6knrhe5#
您可以直接使用
std::ostream
执行的唯一操作是众所周知的<<
-语法:有各种各样的IO manipulators可以用来影响整数、浮点数等的格式、位数等。
然而,这与
printf
的格式化字符串不同。C11不包含任何允许您以与printf
相同的方式使用字符串格式化的工具(除了printf
本身,当然如果您愿意,可以在C中使用它)。就提供
printf
风格功能的库而言,有boost::format
,它支持如下代码(从概要中复制):还要注意的是,在标准的未来版本中有
printf
样式格式的proposal for inclusion。如果这被接受,可能会出现如下语法:nnvyjq4y6#
这是我已经习惯的一个成语,希望它能帮上忙:
&
hmae6n7t7#
我建议使用ostringstream而不是ostream,请参见以下示例:
示例用法:
2ledvvac8#
要实现printf,可以使用c++11模板参数:
这是一个非常简单的代码,它可以改进.
1)优点是它使用〈〈将对象打印到流中,因此您可以放置任意参数,这些参数可以通过〈〈输出。
2)它忽略格式化字符串中参数的类型:%后面可以是任意符号,甚至是空格。2输出流决定如何打印相应的对象。3它与printf兼容。
3)一个缺点是它不能打印百分比符号' %',需要稍微改进代码。
4)它不能打印格式化的数字,如%4.5f
5)如果参数的数目少于格式化字符串所预测的数目,则函数只打印字符串的其余部分。
6)如果参数的数目大于格式化字符串预测的数目,则忽略剩余的参数
你可以改进代码使2)-6)完全模仿printf的行为,但是,如果你遵循printf的规则,那么只有3)和4)需要被修正。
hts6caw39#
我独立编写,但得出的答案与user3283405相似
我的解决方案使用vasprintf()来实现格式设置,并使用std::ostream的〈〈操作符重载来释放正确位置的内存。
用法:
代码:
请注意,编译器不会检查putf()中的格式,因此编译器标志-Wformat-nonliteral不会对putf()中的可疑代码发出警告,您需要自己关注uncontrolled format string问题。
详细信息可在GitHub上找到