basic_string_to_string

basic_string_to_string (숫자 값을 문자열로 변환하는 함수)

std::to_string은 C++ 표준 라이브러리에서 숫자 값을 std::string으로 변환하는 함수예요. 정수 타입과 부동소수점 타입을 모두 지원하며, C++11부터 사용할 수 있어요. 이 페이지에서는 함수의 동작 방식, 매개변수, 반환값, 예외, 그리고 주의사항을 자세히 살펴볼게요.

출처: cppreference

본문

개요

<string> 헤더에 다음 오버로드들이 정의되어 있어요.

<string> 헤더에 정의됨
std::string to_string(int value); (1) (since C++11)
std::string to_string(long value); (2) (since C++11)
std::string to_string(long long value); (3) (since C++11)
std::string to_string(unsigned value); (4) (since C++11)
std::string to_string(unsigned long value); (5) (since C++11)
std::string to_string(unsigned long long value); (6) (since C++11)
std::string to_string(float value); (7) (since C++11)
std::string to_string(double value); (8) (since C++11)
std::string to_string(long double value); (9) (since C++11)

이 함수들은 숫자 값을 std::string으로 변환해요.

동작 방식

buf를 변환 함수 내부의 버퍼라고 할게요. 이 버퍼는 변환 결과를 담을 수 있을 만큼 충분히 커요.

C++26 이전:

  1. 부호 있는 정수를 std::sprintf(buf, "%d", value)로 변환한 것처럼 문자열로 만들어요.
  2. 부호 있는 정수를 std::sprintf(buf, "%ld", value)로 변환한 것처럼 문자열로 만들어요.
  3. 부호 있는 정수를 std::sprintf(buf, "%lld", value)로 변환한 것처럼 문자열로 만들어요.
  4. 부호 없는 정수를 std::sprintf(buf, "%u", value)로 변환한 것처럼 문자열로 만들어요.
  5. 부호 없는 정수를 std::sprintf(buf, "%lu", value)로 변환한 것처럼 문자열로 만들어요.
  6. 부호 없는 정수를 std::sprintf(buf, "%llu", value)로 변환한 것처럼 문자열로 만들어요. 7, 8. 부동소수점 값을 std::sprintf(buf, "%f", value)로 변환한 것처럼 문자열로 만들어요.
  7. 부동소수점 값을 std::sprintf(buf, "%Lf", value)로 변환한 것처럼 문자열로 만들어요.

C++26부터:

1~9. 숫자 값을 std::format("{}", value)로 변환한 것처럼 문자열로 만들어요.

매개변수

매개변수 설명
value 변환할 숫자 값

반환값

변환된 값을 담은 문자열을 반환해요.

예외

std::string 생성자에서 std::bad_alloc을 던질 수 있어요.

참고 사항

  • 부동소수점 타입의 경우, 반환된 문자열의 유효 숫자 개수가 0이 될 수 있어서 std::to_string이 예상치 못한 결과를 낼 수 있어요. 아래 예제를 참고하세요.
  • 반환값은 std::cout이 기본적으로 출력하는 값과 크게 다를 수 있어요. 아래 예제를 참고하세요.

C++26 이전에는 std::to_string이 형식 지정을 위해 현재 C 로케일에 의존했어요. 따라서 여러 스레드에서 동시에 std::to_string을 호출하면 호출이 부분적으로 직렬화될 수 있었어요. 정수 타입 오버로드의 결과는 현재 C 로케일에 의존하지 않으므로, 구현체는 일반적으로 정확성과 성능을 위해 이 오버로드들에서 현재 C 로케일에 접근하는 것을 피했어요. 하지만 표준이 이를 보장하지는 않았어요.

C++17에서는 더 높은 성능의 로케일 독립적 대안으로 std::to_chars를 제공해요.

Feature-test macro 표준 기능
__cpp_lib_to_string 202306L (C++26) std::to_stringstd::format 기반으로 재정의

예제

#include <cstdio>
#include <format>
#include <initializer_list>
#include <iostream>
#include <string>

#if __cpp_lib_to_string >= 202306L
constexpr auto revision() { return " (post C++26)"; }
#else
constexpr auto revision() { return " (pre C++26)"; }
#endif

int main()
{
    for (const double f : {1.23456789555555, 23.43, 1e-9, 1e40, 1e-40, 123456789.0})
    {
        std::cout << "to_string:\t" << std::to_string(f) << revision() << '\n';

        // Before C++26, the output of std::to_string matches std::printf.
        std::printf("printf:\t\t%f\n", f);

        // As of C++26, the output of std::to_string matches std::format.
        std::cout << std::format("format:\t\t{}\n", f);

        std::cout << "std::cout:\t" << f << "\n\n";
    }
}

가능한 출력:

to_string:      1.234568 (pre C++26)
printf:         1.234568
format:         1.23456789555555
std::cout:      1.23457

to_string:      23.430000 (pre C++26)
printf:         23.430000
format:         23.43
std::cout:      23.43

to_string:      0.000000 (pre C++26)
printf:         0.000000
format:         1e-09
std::cout:      1e-09

to_string:      10000000000000000303786028427003666890752.000000 (pre C++26)
printf:         10000000000000000303786028427003666890752.000000
format:         1e+40
std::cout:      1e+40

to_string:      0.000000 (pre C++26)
printf:         0.000000
format:         1e-40
std::cout:      1e-40

to_string:      123456789.000000 (pre C++26)
printf:         123456789.000000
format:         123456789
std::cout:      1.23457e+08

같이 보기

함수 설명
to_wstring (C++11) 정수 또는 부동소수점 값을 wstring으로 변환해요
stoul, stoull (C++11) 문자열을 부호 없는 정수로 변환해요
stoi, stol, stoll (C++11) 문자열을 부호 있는 정수로 변환해요
stof, stod, stold (C++11) 문자열을 부동소수점 값으로 변환해요
to_chars (C++17) 정수 또는 부동소수점 값을 문자 시퀀스로 변환해요

더 알아보기 (Learn more)

cppreference