2012-07-01 3 views
0

i/ostream의 비트 시프트 부울 오버로드를 교체하고 싶습니다. 현재 구현에서는 "0"또는 "1"의 입력 문자열 만 가져 와서 "0"또는 "1"만 출력합니다. 나는 "t", "true", "f", "false"등과 같은 다른 시퀀스를 고려하는 과부하를 만들고 싶다. 제한된 범위에 국한되어 있다고해도 어쨌든이 작업을 수행 할 수 있습니까? 당신은 가능성으로 tf를 삭제하고자하는 경우o/istream bool 비트 시프트 연산자를 대체하십시오.

inline std::ostream& operator << (std::ostream& os, bool b) 
{ 
    return os << ((b) ? "true" : "false"); 
} 

inline std::istream& operator >> (std::istream& is, bool& b) 
{ 
    string s; 
    is >> s; 
    s = Trim(s); 

    const char* true_table[5] = { "t", "T", "true" , "True ", "1" }; 
    const char* false_table[5] = { "f", "F", "false", "False", "0" }; 

    for (uint i = 0; i < 5; ++i) 
    { 
     if (s == true_table[i]) 
     { 
      b = true; 
      return is; 
     } 
    } 

    for (uint i = 0; i < 5; ++i) 
    { 
     if (s == false_table[i]) 
     { 
      b = false; 
      return is; 
     } 
    } 

    is.setstate(std::ios::failbit); 
    return is; 
} 

답변

1

방금 ​​std::boolalpha을 사용할 수 있으며 cppreference에서 std::noboolalpha

:

// boolalpha output 
std::cout << std::boolalpha 
      << "boolalpha true: " << true << '\n' 
      << "boolalpha false: " << false << '\n'; 
std::cout << std::noboolalpha 
      << "noboolalpha true: " << true << '\n' 
      << "noboolalpha false: " << false << '\n'; 
// booalpha parse 
bool b1, b2; 
std::istringstream is("true false"); 
is >> std::boolalpha >> b1 >> b2; 
std::cout << '\"' << is.str() << "\" parsed as " << b1 << ' ' << b2 << '\n'; 

출력이는 내가 사용하고자하는 코드입니다 :

boolalpha true: true 
boolalpha false: false 
noboolalpha true: 1 
noboolalpha false: 0 
"true false" parsed as 1 0 
+0

은 definiti 각 구현마다 다른 boolalpha? – Jim

+0

@ 짐 No. 654321 – David

관련 문제