Convert MFC CString to integer

后端 未结 11 2064
南旧
南旧 2020-12-08 13:15

How to convert a CString object to integer in MFC.

11条回答
  •  既然无缘
    2020-12-08 14:14

    The canonical solution is to use the C++ Standard Library for the conversion. Depending on the desired return type, the following conversion functions are available: std::stoi, std::stol, or std::stoll (or their unsigned counterparts std::stoul, std::stoull).

    The implementation is fairly straight forward:

    int ToInt( const CString& str ) {
        return std::stoi( { str.GetString(), static_cast( str.GetLength() ) } );
    }
    
    long ToLong( const CString& str ) {
        return std::stol( { str.GetString(), static_cast( str.GetLength() ) } );
    }
    
    long long ToLongLong( const CString& str ) {
        return std::stoll( { str.GetString(), static_cast( str.GetLength() ) } );
    }
    
    unsigned long ToULong( const CString& str ) {
        return std::stoul( { str.GetString(), static_cast( str.GetLength() ) } );
    }
    
    unsigned long long ToULongLong( const CString& str ) {
        return std::stoull( { str.GetString(), static_cast( str.GetLength() ) } );
    }
    

    All of these implementations report errors through exceptions (std::invalid_argument if no conversion could be performed, std::out_of_range if the converted value would fall out of the range of the result type). Constructing the temporary std::[w]string can also throw.

    The implementations can be used for both Unicode as well as MBCS projects.

提交回复
热议问题