简体   繁体   中英

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返回它打印的字符数

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.

}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM