code

C ++에서 bool을 텍스트로 변환

codestyles 2020. 9. 18. 08:15
반응형

C ++에서 bool을 텍스트로 변환


아마도 이것은 어리석은 질문이지만, 1이 "true"로 바뀌고 0이 "false"로 바뀌도록 부울 값을 문자열로 변환하는 방법이 있습니까? if 문을 사용할 수 있지만 언어 또는 표준 라이브러리로이를 수행 할 수있는 방법이 있는지 아는 것이 좋습니다. 게다가 저는 pedant입니다. :)


C ++ 언어 자체를 사용하는 것은 어떻습니까?

bool t = true;
bool f = false;
std::cout << std::noboolalpha << t << " == " << std::boolalpha << t << std::endl;        
std::cout << std::noboolalpha << f << " == " << std::boolalpha << f << std::endl;

최신 정보:

당신이 더 많은 코드의 4 개 라인보다 콘솔 출력없이 원하는 경우 방문하십시오 에 대해 이야기 cppreference.com의 페이지 std::boolalphastd::noboolalpha 어떤 쇼 당신에게 콘솔 출력을하고 더 많은 API에 대해 설명합니다.

또한를 사용 std::boolalpha하면의 전역 상태가 수정됩니다 std::cout. 원래 동작을 복원 할 수 있습니다 . 상태 복원에 대한 자세한 내용을 보려면 여기로 이동하십시오std::cout .


우리는 C ++에 대해 이야기하고 있습니까? 왜 우리는 여전히 매크로를 사용하고 있습니까!?

C ++ 인라인 함수는 매크로와 동일한 속도를 제공하며 형식 안전성 및 매개 변수 평가의 추가 이점 (Rodney 및 dwj가 언급 한 문제를 방지합니다.

inline const char * const BoolToString(bool b)
{
  return b ? "true" : "false";
}

그 외에도 특히 받아 들여지는 답변에 대해 몇 가지 다른 불만이 있습니다. :)

// this is used in C, not C++. if you want to use printf, instead include <cstdio>
//#include <stdio.h>
// instead you should use the iostream libs
#include <iostream>

// not only is this a C include, it's totally unnecessary!
//#include <stdarg.h>

// Macros - not type-safe, has side-effects. Use inline functions instead
//#define BOOL_STR(b) (b?"true":"false")
inline const char * const BoolToString(bool b)
{
  return b ? "true" : "false";
}

int main (int argc, char const *argv[]) {
    bool alpha = true;

    // printf? that's C, not C++
    //printf( BOOL_STR(alpha) );
    // use the iostream functionality
    std::cout << BoolToString(alpha);
    return 0;
}

건배 :)


@DrPizza : 이렇게 간단한 기능을 위해 전체 부스트 라이브러리를 포함 시키시겠습니까? 농담이야?


C ++에는 적절한 문자열이 있으므로 사용하는 것이 좋습니다. 표준 헤더 문자열에 있습니다. #include <string>을 사용합니다. 더 이상 strcat / strcpy 버퍼 오버런이 없습니다. 더 이상 null 종결자가 누락되지 않습니다. 더 이상 복잡한 수동 메모리 관리가 없습니다. 적절한 값 의미를 가진 적절한 계수 문자열.

C++ has the ability to convert bools into human-readable representations too. We saw hints at it earlier with the iostream examples, but they're a bit limited because they can only blast the text to the console (or with fstreams, a file). Fortunately, the designers of C++ weren't complete idiots; we also have iostreams that are backed not by the console or a file, but by an automatically managed string buffer. They're called stringstreams. #include <sstream> to get them. Then we can say:

std::string bool_as_text(bool b)
{
    std::stringstream converter;
    converter << std::boolalpha << b;   // flag boolalpha calls converter.setf(std::ios_base::boolalpha)
    return converter.str();
}

Of course, we don't really want to type all that. Fortunately, C++ also has a convenient third-party library named Boost that can help us out here. Boost has a nice function called lexical_cast. We can use it thus:

boost::lexical_cast<std::string>(my_bool)

Now, it's true to say that this is higher overhead than some macro; stringstreams deal with locales which you might not care about, and create a dynamic string (with memory allocation) whereas the macro can yield a literal string, which avoids that. But on the flip side, the stringstream method can be used for a great many conversions between printable and internal representations. You can run 'em backwards; boost::lexical_cast<bool>("true") does the right thing, for example. You can use them with numbers and in fact any type with the right formatted I/O operators. So they're quite versatile and useful.

And if after all this your profiling and benchmarking reveals that the lexical_casts are an unacceptable bottleneck, that's when you should consider doing some macro horror.


This should be fine:


const char* bool_cast(const bool b) {
    return b ? "true" : "false";
}

But, if you want to do it more C++-ish:


#include <iostream>
#include <string>
#include <sstream>
using namespace std;

string bool_cast(const bool b) {
    ostringstream ss;
    ss << boolalpha << b;
    return ss.str();
}

int main() {
    cout << bool_cast(true) << "\n";
    cout << bool_cast(false) << "\n";
}

If you decide to use macros (or are using C on a future project) you should add parenthesis around the 'b' in the macro expansion (I don't have enough points yet to edit other people's content):

#define BOOL_STR(b) ((b)?"true":"false")

This is a defensive programming technique that protects against hidden order-of-operations errors; i.e., how does this evaluate for all compilers?

1 == 2 ? "true" : "false"

compared to

(1 == 2) ? "true" : "false"

I use a ternary in a printf like this:

printf("%s\n", b?"true":"false");

If you macro it :

B2S(b) ((b)?"true":"false")

then you need to make sure whatever you pass in as 'b' doesn't have any side effects. And don't forget the brackets around the 'b' as you could get compile errors.


With C++11 you might use a lambda to get a slightly more compact code and in place usage:

bool to_convert{true};
auto bool_to_string = [](bool b) -> std::string {
    return b ? "true" : "false";
};
std::string str{"string to print -> "};
std::cout<<str+bool_to_string(to_convert);

Prints:

string to print -> true

This post is old but now you can use std::to_string to convert a lot of variable as std::string.

http://en.cppreference.com/w/cpp/string/basic_string/to_string


Use boolalpha to print bool to string.

std::cout << std::boolalpha << b << endl;
std::cout << std::noboolalpha << b << endl;

C++ Reference


Without dragging ostream into it:

constexpr char const* to_c_str(bool b) {
   return  
    std::array<char const*, 2>{"false", "true "}[b]
   ;
};

I agree that a macro might be the best fit. I just whipped up a test case (believe me I'm no good with C/C++ but this sounded fun):

#include <stdio.h>
#include <stdarg.h>

#define BOOL_STR(b) (b?"true":"false")

int main (int argc, char const *argv[]) {
    bool alpha = true;
    printf( BOOL_STR(alpha) );
    return 0;
}

As long as strings can be viewed directly as a char array it's going to be really hard to convince me that std::string represents strings as first class citizens in C++.

Besides, combining allocation and boundedness seems to be a bad idea to me anyways.


Try this Macro. Anywhere you want the "true" or false to show up just replace it with PRINTBOOL(var) where var is the bool you want the text for.

#define PRINTBOOL(x) x?"true":"false"

참고URL : https://stackoverflow.com/questions/29383/converting-bool-to-text-in-c

반응형