[C++] std::string(wstring) ->숫자 변환

빵욱·2025년 1월 16일

std::string, wstring를 정수형, 부동소수점 타입으로 변환해서 사용할 때가 많다.

문자열 데이터에 크기초과 또는 변환 시 이상한 데이터가 있으면 처리해줘야해서 공용함수로 아래와 같이 만들어서 사용했다..

int CXKDoc::Safe_stoi(const std::wstring& wstrInput)
{
    try
    {
        return std::stoi(wstrInput); // std::wstring을 int로 변환
    }
    catch (const std::invalid_argument&)
    {
        return 0; // 변환 실패 시 기본값 반환
    }
    catch (const std::out_of_range&)
    {
        return 0; // 변환 실패 시 기본값 반환
    }
    catch (const std::exception&)
    {
        return 0; // 기타 예외 발생 시 기본값 반환
    }
}

float, double형을 사용하고 싶으면 std::stof, stod를 사용..

profile
rove drink eat

0개의 댓글