2016-02-12 46 views
0

此問題與:Get number of characters read by sscanf? 然而,它特別要求如何包裝可變參數(C++ 11 variadic模板)以實現該效果。獲取通過包裝函數使用std :: sscanf函數掃描的字符數。擴展可變參數模板

我想有一個函數:

int my_sscanf(int& ncharswritten, const char* str, const char* fmt, ...) 
{ 
} 

返回的指定格式事物的正常數量,但還(如例如參考參數)返回寫入的字符數。

正如在上面的鏈接中提到的,建議的解決方法是知道寫入的字符數是使用fmt末尾的%n。問題是如何在現實生活中實現這一點,而不必每次都手動添加。

+0

您需要%N'加上'以某種方式格式字符串。最簡單的'std :: string fmt2 = fmt +「%n」; ... sscanf(... fmt2.c_str()...);' –

+0

Thanks Mats,魔鬼詳細介紹瞭如何在可變參數列表末尾添加所需的額外int *參數到sscanf( ),將%n添加到fmt的結尾後。 – rveale

回答

1

您可以使用類似:

template <typename...Ts> 
int my_sscanf(int& ncharswritten, const char* str, const char* fmt, Ts&&...ts) 
{ 
    return sscanf(std, 
        (fmt + std::string("%n")).c_str(), 
        std::forward<Ts>(ts)..., 
        &ncharswritten); 
} 
+0

感謝jarod,這基本上是我發現的,我會接受你的答案。我不明白它的std :: forward 部分,或者Ts &&位。 – rveale

+0

這是轉發參數(保留常量,右值/左值,...)的方式。在你的情況下通過複製應該沒問題,參數是指針(所以'Ts * ... ts'可能會更好)。 – Jarod42

+0

啊,我明白了。在sscanf的情況下,他們總是指針,所以我想我只是在這種情況下幸運?我的例子下面的原因是某些原因... – rveale

0

我解決了問題,有點繞纏着後:

template<typename... Args> 
    int my_scanf(int& nchars, const std::string& buffer, const char* fmt, Args... args) 
    { 

    std::string fmtstr = std::string(fmt); 
    fmtstr+="%n"; 
    nchars=-1; 

    int nargswritten = std::sscanf(buffer.c_str(), fmtstr.c_str(), args..., &nchars); 

    fprintf(stdout, "I consumed [%d] chars\n", nchars); 


    //REV: This won't work if it goes past EOF, so need to handle how many were written if conspos wasn't filled becuase 
    //it hit EOF partway through... 
    return (nargswritten-1); //REV: subtracting one because of added %n 

    } 
相關問題