有谁知道我如何打印和计算我打印的字符数?
说我有一个号码,我通过printf
或cout
打印。我怎么能算出我打印出来的实际位数?
答案 0 :(得分:9)
答案 1 :(得分:7)
printf返回它打印的字符数
答案 2 :(得分:3)
这是滥用Locale在senes后面进行计数的另一种创造性方法 这允许您正常使用流,本地将为您记录输出。
这不是生产就绪代码,只是一个概念证明,以展示如何做到这一点:
#include <locale>
#include <iostream>
#include <fstream>
class Counter: public std::codecvt<char,char,std::char_traits<char>::state_type>
{
public:
Counter(int& count)
:m_count(&count)
{}
private:
typedef std::codecvt<char,char,std::char_traits<char>::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.
}
答案 3 :(得分:0)
如果您想使用ostream
,pcount()
会返回放置的字符数。
答案 4 :(得分:0)
使用字符串流预先转换,然后轮询该长度。