开发者

How can I count the number of characters that are printed as output?

Does anyone know how I can print and count the number of characters that I printed?

Say I have a number I开发者_运维技巧 am printing via printf or cout. How could I count the actual number of digits I have printed out?


According to the printf man page, printf returns the number of characters printed.

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

If an output error is encountered, a negative value is returned.


printf returns the number of characters it printed


Here is another creative way of abusing the Locale to do the counting behind the senes.
This allows you to use the stream normally and the local will record the output for you.

This is not production ready code just a proof of concept to show how it could be done:

#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.

}


If you want to use an ostream, pcount() returns the number of characters put.


Use a stringstream to convert beforehand, then poll that for the length.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜