문제

이 질문은 이미 여기에 답이 있습니다.

대안이 있는지 궁금합니다 itoa() 정수를 문자열로 변환하기 위해 Visual Studio에서 실행할 때 경고를 받고 Linux에서 프로그램을 구축하려고하면 컴파일 오류가 발생합니다.

도움이 되었습니까?

해결책

C ++ 11에서는 사용할 수 있습니다 std::to_string:

#include <string>

std::string s = std::to_string(5);

C ++ 11 이전에 작업하는 경우 C ++ 스트림을 사용할 수 있습니다.

#include <sstream>

int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();

가져 왔습니다 http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/

다른 팁

부스트 :: lexical_cast 꽤 잘 작동합니다.

#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
    std::string foo = boost::lexical_cast<std::string>(argc);
}

고고학

ITOA는 ATOI 표준 기능을 보완하도록 설계된 비표준 도우미 기능이었으며 아마도 Sprintf를 숨기고있을 것입니다 (대부분의 기능은 Sprintf 측면에서 구현 될 수 있음). http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html

C 웨이

Sprintf를 사용하십시오. 또는 snprintf. 또는 찾은 도구.

사실에도 불구하고 일부 기능은 표준에 있지 않지만, 그의 의견 중 하나에서 "OneByone"이 올바르게 언급했듯이, 대부분의 컴파일러는 대안을 제공합니다 (예 : Visual C ++에는 필요한 경우 snprintf에 입력 할 수있는 자체 _snprintf가 있습니다).

C ++ 방법.

C ++ 스트림을 사용하십시오 (현재의 경우 std :: stringstream (또는 허브 셔터가 그의 책 중 하나에서 제안한대로 더 이상 사용되지 않은 std :: strstream에서도 다소 빠르기 때문에).

결론

C ++에 있습니다. 즉, 원하는 방식으로 선택할 수 있습니다.

  • 더 빠른 방법 (예 : C 방식)이지만, 코드가 응용 프로그램의 병목 현상 (조기 최적화는 사악한 등)이며 버퍼 오버런 위험을 피하기 위해 코드가 안전하게 캡슐화되어 있는지 확인해야합니다.

  • 더 안전한 방법 (예 : C ++ 방법), 코드 의이 부분이 중요하지 않다는 것을 알고 있다면 누군가가 크기 나 포인터를 착각하기 때문에 코드 의이 부분이 임의의 순간에 깨지지 않도록하는 것이 좋습니다 (발생합니다. 실생활에서, 어제, 내 컴퓨터에서 누군가가 실제로 필요하지 않고 더 빠른 길을 사용하는 것이 "멋지다"고 생각했기 때문에).

sprintf () : 시도 :

char str[12];
int num = 3;
sprintf(str, "%d", num); // str now contains "3"

sprintf ()는 printf ()와 같지만 문자열로 출력합니다.

또한 주석에서 Parappa가 언급했듯이 Snprintf ()를 사용하여 버퍼 오버플로가 발생하지 않도록 할 수 있습니다 (변환 숫자가 문자열의 크기에 맞지 않는 경우) : 다음과 같이 작동합니다.

snprintf(str, sizeof(str), "%d", num);

무대 뒤에서 Lexical_cast는 다음을 수행합니다.

std::stringstream str;
str << myint;
std::string result;
str >> result;

이를 위해 "드래그"하고 싶지 않다면 위를 사용하는 것이 좋은 솔루션입니다.

우리는 우리 자신을 정의 할 수 있습니다 iota C ++에서 기능 :

string itoa(int a)
{
    string ss="";   //create empty string
    while(a)
    {
        int x=a%10;
        a/=10;
        char i='0';
        i=i+x;
        ss=i+ss;      //append new character at the front of the string!
    }
    return ss;
}

잊지 마세요 #include <string>.

с ++ 11은 마침내이 제공을 해결합니다 std::to_string. 또한 boost::lexical_cast 이전 컴파일러를위한 편리한 도구입니다.

이 템플릿을 사용합니다

template <typename T> string toStr(T tmp)
{
    ostringstream out;
    out << tmp;
    return out.str();
}


template <typename T> T strTo(string tmp)
{
    T output;
    istringstream in(tmp);
    in >> output;
    return output;
}

노력하다 boost.format 또는 FastFormat, 고품질 C ++ 라이브러리 :

int i = 10;
std::string result;

boost.format

result = str(boost::format("%1%", i));

또는 FastFormat

fastformat::fmt(result, "{0}", i);
fastformat::write(result, i);

분명히 그들은 둘 다 단일 정수의 간단한 변환보다 훨씬 더 많은 일을합니다.

실제로 하나의 영리하게 쓰여진 템플릿 함수로 문자열로 모든 것을 변환 할 수 있습니다. 이 코드 예제는 루프를 사용하여 Win-32 시스템에서 하위 디렉터를 생성합니다. 문자열 연결 연산자 인 Operator+는 디렉토리 이름을 생성하기 위해 접미사와 루트를 연결하는 데 사용됩니다. 접미사는 루프 제어 변수 i를 C ++ 문자열로 변환하여 템플릿 함수를 사용하여 다른 문자열과 연결하여 생성됩니다.

//Mark Renslow, Globe University, Minnesota School of Business, Utah Career College
//C++ instructor and Network Dean of Information Technology

#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream> // string stream
#include <direct.h>

using namespace std;

string intToString(int x)
{
/**************************************/
/* This function is similar to itoa() */
/* "integer to alpha", a non-standard */
/* C language function. It takes an   */
/* integer as input and as output,    */
/* returns a C++ string.              */
/* itoa()  returned a C-string (null- */
/* terminated)                        */
/* This function is not needed because*/
/* the following template function    */
/* does it all                        */
/**************************************/   
       string r;
       stringstream s;

       s << x;
       r = s.str();

       return r;

}

template <class T>
string toString( T argument)
{
/**************************************/
/* This template shows the power of   */
/* C++ templates. This function will  */
/* convert anything to a string!      */
/* Precondition:                      */
/* operator<< is defined for type T    */
/**************************************/
       string r;
       stringstream s;

       s << argument;
       r = s.str();

       return r;

}

int main( )
{
    string s;

    cout << "What directory would you like me to make?";

    cin >> s;

    try
    {
      mkdir(s.c_str());
    }
    catch (exception& e) 
    {
      cerr << e.what( ) << endl;
    }

    chdir(s.c_str());

    //Using a loop and string concatenation to make several sub-directories
    for(int i = 0; i < 10; i++)
    {
        s = "Dir_";
        s = s + toString(i);
        mkdir(s.c_str());
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}

충분한 길이를 할당 한 다음 snprintf를 사용하십시오.

가장 좋은 답변 인 IMO는 여기에 제공된 기능입니다.

http://www.jb.man.ac.uk/~slowe/cpp/itoa.html

그것은 많은 Libs에서 제공하는 비 ANSI 기능을 모방합니다.

char* itoa(int value, char* result, int base);

또한 번개가 빠르고 -o3에서 잘 최적화되며 C ++ String_format ()를 사용하지 않는 이유는 너무 느리기 때문입니다.

모든 것입니다 stringstream 행동 양식 5월 형식을 위해 로케일 객체의 사용 주위를 잠그는 것과 관련이 있습니다. 이것 5월 여러 스레드 에서이 변환을 사용하고 있다면 조심해야 할 일이 되십시오 ...

자세한 내용은 여기를 참조하십시오. C ++의 길이가 지정된 문자열로 숫자를 변환합니다.

int number = 123;

stringstream = s;

s << number;

cout << ss.str() << endl;

금속 정수뿐만 아니라 String to String 변환 방법에 관심이 있고 표준 라이브러리에만 국한되지 않는다면 FormatInt .의 방법 C ++ 형식 도서관:

fmt::FormatInt(42).str();   // convert to std::string
fmt::FormatInt(42).c_str(); // convert and get as a C string
                            // (mind the lifetime, same as std::string::c_str())

에 따르면 정수로 문자열 변환 벤치 마크 Boost Karma 에서이 방법은 Glibc의 것보다 몇 배 더 빠릅니다. sprintf 또는 std::stringstream. Karma 자신의 부스트보다 훨씬 빠릅니다 int_generator an에 의해 확인 된 바와 같이 독립적 인 벤치 마크.

면책 조항 : 저는이 도서관의 저자입니다.

나는 이것을 썼다 스레드 안전 얼마 전에 기능하고 결과에 매우 만족하고 알고리즘이 가볍고 마른 느낌이 들며 표준 MSVC _itoa () 함수의 약 3 배의 성능이 있습니다.

여기 링크가 있습니다. 최적의 Base-10 Only itoa () 함수? Sprintf ()의 성능은 10 배 이상입니다. 벤치 마크는 다음과 같이 기능의 QA 테스트입니다.

start = clock();
for (int i = LONG_MIN; i < LONG_MAX; i++) {
    if (i != atoi(_i32toa(buff, (int32_t)i))) {
        printf("\nError for %i", i);
    }
    if (!i) printf("\nAt zero");
}
printf("\nElapsed time was %f milliseconds", (double)clock() - (double)(start));

발신자의 스토리지를 사용하는 것에 대한 몇 가지 어리석은 제안이 있습니다. 결과는 발신자의 주소 공간의 버퍼 어딘가에 떠 다니는 결과를 남길 수 있습니다. 그들을 무시하라. 벤치 마크/QA 코드가 보여준 것처럼 내가 나열된 코드는 완벽하게 작동합니다.

이 코드는 임베디드 환경에서 사용할 수있을 정도로 마른 것으로 생각합니다. 물론 YMMV.

Windows CE 파생 플랫폼에는 아니요 iostream기본적으로 s. 가는 길은 _itoa<> 가족, 보통 _itow<> (어쨌든 대부분의 스트링 물건은 유니 코드이기 때문에).

위의 제안의 대부분은 기술적으로 C ++가 아니며 C 솔루션이 아닙니다.

사용을 조사하십시오 std :: stringstream.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top