Programing

int에서 char *로 변환하는 방법?

lottogame 2020. 9. 3. 23:35
반응형

int에서 char *로 변환하는 방법?


내가 아는 유일한 방법은 다음과 같습니다.

#include <sstream>
#include <string.h>
using namespace std;

int main() {
  int number=33;
  stringstream strs;
  strs << number;
  string temp_str = strs.str();
  char* char_type = (char*) temp_str.c_str();
}

그러나 타이핑이 적은 방법이 있습니까?


  • C ++ 17에서는 다음 std::to_chars과 같이 사용 합니다.

    std::array<char, 10> str;
    std::to_chars(str.data(), str.data() + str.size(), 42);
    
  • C ++ 11에서는 다음 std::to_string과 같이 사용 합니다.

    std::string s = std::to_string(number);
    char const *pchar = s.c_str();  //use char const* as target type
    
  • 그리고 C ++ 03에서는 다음 const과 같이 사용 하는 것을 제외하고는 괜찮습니다 .

    char const* pchar = temp_str.c_str(); //dont use cast
    

sprintf를 사용할 수 있다고 생각합니다.

int number = 33;
char* numberstring[(((sizeof number) * CHAR_BIT) + 2)/3 + 2];
sprintf(numberstring, "%d", number);

부스트를 사용할 수 있습니다

#include <boost/lexical_cast.hpp>
string s = boost::lexical_cast<string>( number );

C 스타일 솔루션은를 사용하는 itoa것이지만 더 좋은 방법은 sprintf/snprintf 를 사용하여이 숫자를 문자열로 인쇄하는 것 입니다. 이 질문을 확인하십시오 : 정수를 이식 가능하게 문자열로 변환하는 방법?

참고 itoa함수는 ANSI-C에 정의되지 않은 및 C ++의 일부가 아니라, 어떤 컴파일러에 의해 지원된다. 비표준 기능이므로 사용을 피해야합니다. 이 질문도 확인하십시오 : 정수를 문자열 C ++로 변환하는 itoa ()의 대안입니까?

또한 C ++로 프로그래밍하는 동안 C 스타일 코드를 작성하는 것은 나쁜 습관으로 간주되며 때때로 "끔찍한 스타일"이라고도합니다. 정말 C 스타일 char*문자열 로 변환 하시겠습니까? :)


나는 이유가 있기 때문에 마지막 줄에서 const를 typecast하지 않을 것입니다. const char *로 살 수 없다면 다음과 같이 char 배열을 복사하는 것이 좋습니다.

char* char_type = new char[temp_str.length()];
strcpy(char_type, temp_str.c_str());

이 답변 참조 https://stackoverflow.com/a/23010605/2760919

귀하의 경우 snprintf의 유형을 long ( "% ld")에서 int ( "% n")로 변경하십시오.


캐스팅을 사용할 수도 있습니다.

예:

string s;
int value = 3;
s.push_back((char)('0' + value));

이것은 조금 늦었을 수도 있지만 같은 문제가있었습니다. char 로의 변환은 "charconv"라이브러리를 사용하여 C ++ 17에서 해결되었습니다.

https://en.cppreference.com/w/cpp/utility/to_chars


Alright.. firstly I needed something that did what this question is asking, but I needed it FAST! Unfortunately the "better" way is nearly 600 lines of code!!! Pardon the name of it that doesn't have anything to do with what it's doing. Proper name was Integer64ToCharArray(int64_t value);

https://github.com/JeremyDX/All-Language-Testing-Code/blob/master/C%2B%2B%20Examples/IntegerToCharArrayTesting.cpp

Feel free to try cleaning that code up without hindering performance.

Input: Any signed 64 bit value from min to max range.

Example:

std::cout << "Test: " << AddDynamicallyToBuffer(LLONG_MAX) << '\n';
std::cout << "Test: " << AddDynamicallyToBuffer(LLONG_MIN) << '\n';

Output:

Test: 9223372036854775807
Test: -9223372036854775808

Original Speed Tests: (Integer64ToCharArray();)

Best case 1 digit value.

Loops: 100,000,000, Time Spent: 1,381(Milli), Time Per Loop 13(Nano)

Worse Case 20 Digit Value.

Loops: 100,000,000, Time Spent: 22,656(Milli), Time Per Loop 226(Nano

New Design Speed Tests: (AddDynamicallyToBuffer();)

Best case 1 digit value.

Loops: 100,000,000, Time Spent: 427(Milli), Time Per Loop 4(Nano)

32 Bit Worst Case - 11 digit Value.

Loops: 100,000,000, Time Spent: 1,991(Milli), Time Per Loop 19(Nano)

Negative 1 Trillion Worst Case - 14 digit Value.

Loops: 100,000,000, Time Spent: 5,681(Milli), Time Per Loop 56(Nano)

64 Bit Worse Case - 20 Digit Value.

Loops: 100,000,000, Time Spent: 13,148(Milli), Time Per Loop 131(Nano)

How It Works!

We Perform a Divide and Conquer technique and once we now the maximum length of the string we simply set each character value individually. As shown in above speed tests the larger lengths get big performance penalties, but it's still far faster then the original loop method and no code has actually changed between the two methods other then looping is no longer in use.

In my usage hence the name I return the offset instead and I don't edit a buffer of char arrays rather I begin updating vertex data and the function has an additional parameter for offset so it's not initialized to -1.

참고URL : https://stackoverflow.com/questions/10847237/how-to-convert-from-int-to-char

반응형