programing tip

std :: lexical_cast-그런 것이 있습니까?

itbloger 2020. 10. 27. 07:54
반응형

std :: lexical_cast-그런 것이 있습니까?


C ++ 표준 라이브러리가이 함수를 정의합니까, 아니면 Boost에 의존해야합니까?

웹을 검색했는데 Boost 외에는 아무것도 찾지 못했지만 여기서 물어 보는 것이 좋겠다고 생각했습니다.


부분적으로 만.

C ++ 11 <string>에는 std::to_string내장 유형이 있습니다.

[n3290: 21.5/7]:

string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);

결과 : 각 기능 복귀 string호출에 의해 생성 될 인수의 값의 문자 표현 들고 객체 sprintf(buf, fmt, val)의 포맷 지시자로는 "%d", "%u", "%ld", "%lu", "%lld", "%llu", "%f", "%f", 또는 "%Lf"각각 buf충분한 크기의 내부 문자 버퍼를 나타낸다.

다른 방향으로 이동하는 다음도 있습니다.

[n3290: 21.5/1, 21.5/4]:

int stoi(const string& str, size_t *idx = 0, int base = 10);
long stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);
long long stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);
float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);

그러나 사용할 수있는 일반적인 것은 없으며 (적어도 TR2까지는 아닐 수도 있습니다!) C ++ 03에서는 전혀 사용할 수 없습니다.


아니요, C ++ 11에서도 마찬가지지만 다음 표준 라이브러리 확장 세트 인 기술 보고서 ​​2 에 포함되도록 제안되었습니다 .


std :: lexical_cast는 없지만 항상 stringstreams 와 비슷한 작업을 수행 할 수 있습니다 .

template <typename T>
T lexical_cast(const std::string& str)
{
    T var;
    std::istringstream iss;
    iss.str(str);
    iss >> var;
    // deal with any error bits that may have been set on the stream
    return var;
}

그것은 순수한 Boost 일뿐입니다.


부스트를 원하지 않는 경우 fmt 라는 경량 라이브러리 가 다음을 구현합니다.

// Works with all the C++11 features and AFAIK faster then boost or standard c++11
std::string string_num = fmt::format_int(123456789).str(); // or .c_str()

공식 페이지 에서 더 많은 예 .

위치로 인수에 액세스 :

format("{0}, {1}, {2}", 'a', 'b', 'c');
// Result: "a, b, c"
format("{}, {}, {}", 'a', 'b', 'c');
// Result: "a, b, c"
format("{2}, {1}, {0}", 'a', 'b', 'c');
// Result: "c, b, a"
format("{0}{1}{0}", "abra", "cad");  // arguments' indices can be repeated
// Result: "abracadabra"

텍스트 정렬 및 너비 지정 :

format("{:<30}", "left aligned");
// Result: "left aligned                  "
format("{:>30}", "right aligned");
// Result: "                 right aligned"
format("{:^30}", "centered");
// Result: "           centered           "
format("{:*^30}", "centered");  // use '*' as a fill char
// Result: "***********centered***********"

% + f, % -f 및 % f 대체 및 부호 지정 :

format("{:+f}; {:+f}", 3.14, -3.14);  // show it always
// Result: "+3.140000; -3.140000"
format("{: f}; {: f}", 3.14, -3.14);  // show a space for positive numbers
// Result: " 3.140000; -3.140000"
format("{:-f}; {:-f}", 3.14, -3.14);  // show only the minus -- same as '{:f}; {:f}'
// Result: "3.140000; -3.140000"

% x 및 % o를 대체하고 값을 다른 기준으로 변환 :

format("int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
// Result: "int: 42;  hex: 2a;  oct: 52; bin: 101010"
// with 0x or 0 or 0b as prefix:
format("int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}", 42);
// Result: "int: 42;  hex: 0x2a;  oct: 052;  bin: 0b101010"

참고URL : https://stackoverflow.com/questions/8065413/stdlexical-cast-is-there-such-a-thing

반응형