1

整数型でテンプレート化された C++ クラスがあります。

template<typename int_type>

sscanfそのクラスのどこかで、ファイルからいくつかの値を読み取るために使用したいとします。

int_type num_rows;
fgets( buffer, BUFSIZE, in_file );
sscanf( buffer, "%d", &num_rows);

int_typeフォーマット指定子は、 が組み込みの である場合にのみ正しく機能しますint

一般の書式指定子を処理するより良い方法はありますint_typeか?

4

3 に答える 3

7

と を使用する代わりにsscanf()、フォーマット指定子を次のように使用std::istringstreamoperator>>()ます。

if (fgets( buffer, BUFSIZE, in_file ))
{
    std::istringstream in(buffer);
    if (!(in >> num_rows))
    {
        // Handle failure.
    }
}

FILE*(図示せず)と を aに置き換えると、std::ifstreamを削除でき、代わりにstd::istringstreamから直接読み取ることができます。std::ifstream

于 2013-04-10T14:56:31.180 に答える
3

クラスで宣言するだけfmtで、実装で型ごとに明示的な値を提供できます。

// foo.hpp
template< typename T >
class foo
{
private:
    static const char* fmt;

public:
    void print() const
    {
        T num_rows;
        fgets( buffer, BUFSIZE, in_file );
        sscanf( buffer, fmt, &num_rows);
    }
};

// foo.cpp
template<> const char* foo< int >::fmt = "%d";
template<> const char* foo< long >::fmt = "%ld";
于 2013-04-10T15:28:18.697 に答える