2010-01-14 59 views

回答

9

按照printf man page,printf的返回打印的字符数。

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

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

+1

这是否适用于需要以十进制打印的十六进制字符串?例如1b = 27但printf计数是3? – 2010-01-14 17:40:14

+0

也许我误解了你的问题,但以下为我返回了2。 int count = printf(“%d”,0x1b); – jschmier 2010-01-14 17:55:12

+0

嗯我想输出一个有十六进制字符串的字节数组。所以恰好是1b的字符串。那现在更有意义了吗? – 2010-01-14 18:05:20

7

printf的返回的字符数它印

0

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

+0

我发现['std :: ostrstream :: pcount()'](http://en.cppreference.com/w/cpp/io/ostrstream/pcount),但我找不到'std :: ostream :: pcount( )'。你确定它是标准的吗? – Scheff 2017-08-02 10:51:53

+0

我的意思是'std :: ostrstream'。哎呀。 – 2017-08-02 23:08:30

3

这是另一种滥用Locale进行计数的创造性方法。
这使您可以正常使用流,本地会为您记录输出。

这不是生产做好准备代码只是一个概念的证据证明它可以怎么做:

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

} 
0

使用一个字符串流事先进行转换,然后查询,对于长度。