如何计算作为输出打印的字符数?

有谁知道我如何打印和计算我打印的字符数?

假设我有一个号码,我通过printfcout打印。 我怎么能算出我打印出来的实际位数?

根据printf手册页 ,printf返回打印的字符数。

 int count = printf("%d", 1000); 

如果遇到输出错误,则返回负值。

printf返回它打印的字符数

这是滥用Locale在senes后面进行计数的另一种创造性方法。
这允许您正常使用流,本地将为您记录输出。

这不是生产就绪代码,只是一个概念certificate,以展示如何完成它:

 #include  #include  #include  class Counter: public std::codecvt::state_type> { public: Counter(int& count) :m_count(&count) {} private: typedef std::codecvt::state_type> MyType; typedef MyType::state_type state_type; typedef MyType::result result; virtual bool do_always_noconv() const throw() { return false; } virtual result do_out ( state_type& state, const char* fr, const char* fe, const char*& fn, char* to, char* te, char*& tn ) const { // Count the number of characters that will be out on the stream (*m_count) += (fe - fr); // Use the default do_out (which just copies when internal and external are char) return MyType::do_out(state,fr,fe,fn,to,te,tn); } private: int* m_count; }; int main() { // The variable to store the count in int count = 0; // A local object that contains the counting facet. // The counting facet will record output into count. std::locale countingLocale(std::cout.getloc(), new Counter(count)); std::ofstream data; data.imbue(countingLocale); // Impue the stream before opening. data.open("Plop"); data << "Stop" << std::endl; std::cout << "Count: " << count << "\n"; // This should also work with std::cout std::cout.imbue(countingLocale) // Unfortunately there is a bug in the locale code for me that stops this working. } 

如果要使用ostreampcount()将返回放置的字符数。

使用字符串流预先转换,然后轮询该长度。