C++에서 int
을 동등한 string
으로 변환하는 가장 쉬운 방법은 무엇입니까? 나는 두 가지 방법을 알고있다. 더 쉬운 방법이 있습니까?
(1)
int a = 10;
char *intStr = itoa(a);
string str = string(intStr);
(2)
int a = 10;
stringstream ss;
ss << a;
string str = ss.str();
C++ 11은 C atoi
과 itoa
에 해당하는 std::stoi
(및 각 숫자 유형의 변형) 및 std::to_string
를 소개하지만 std::string
라는 용어로 표현됩니다.
#include <string>
std::string s = std::to_string(42);
그러므로 내가 생각할 수있는 가장 짧은 길입니다. auto
키워드를 사용하여 유형의 이름을 생략 할 수도 있습니다.
auto s = std::to_string(42);
참고 : [string.conversions] ( 21.5 in n3242 )
몇 년 후 @ v.oddou과 토론을 시작한 C++ 17은 마침내 원래 매크로 기반 유형에 관계없이 솔루션을 수행하는 방법을 제공했습니다 (아래에 보존 됨) without 못생긴.
// variadic template
template < typename... Args >
std::string sstr( Args &&... args )
{
std::ostringstream sstr;
// fold expression
( sstr << std::dec << ... << args );
return sstr.str();
}
용법:
int i = 42;
std::string s = sstr( "i is: ", i );
puts( sstr( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) );
원래 답변 :
"문자열로 변환"은 반복되는 문제이므로 항상 C++ 소스의 중앙 헤더에 SSTR () 매크로를 정의합니다.
#include <sstream>
#define SSTR( x ) static_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
사용법은 다음과 같이 쉽습니다.
int i = 42;
std::string s = SSTR( "i is: " << i );
puts( SSTR( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( SSTR( "Foo is '" << x << "', i is " << i ) );
위의 내용은 C++ 98과 호환되며 (C++ 11 std::to_string
를 사용할 수없는 경우) 타사 포함이 필요하지 않습니다 (Bost lexical_cast<>
를 사용할 수없는 경우). 이 두 가지 솔루션 모두 더 나은 성능을 제공합니다.
나는 보통 다음과 같은 방법을 사용한다.
#include <sstream>
template <typename T>
std::string NumberToString ( T Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
here 에 자세히 설명되어 있습니다.
아마도 가장 쉬운 방법은 Boost 에있는 것과 같이 lexical_cast
라는 템플리트에 본질적으로 두 번째 선택 사항을 래핑하는 것이므로 코드는 다음과 같습니다.
int a = 10;
string s = lexical_cast<string>(a);
이것의 한 가지 좋은 점은 다른 캐스트도 지원한다는 것입니다 (예를 들어, 반대 방향으로도 잘 작동 함).
또한 Boost lexical_cast가 문자열 스트림에 쓰는 것으로 시작한 다음 스트림에서 다시 추출하면 이제 몇 가지 추가 사항이 있음을 유의하십시오. 우선, 꽤 많은 유형을위한 전문화가 추가되었으므로 많은 일반적인 유형에서 문자열 스트림을 사용하는 것보다 훨씬 빠릅니다. 둘째, 이제 결과를 확인합니다. 예를 들어 문자열에서 int
으로 변환하면 문자열에 int
으로 변환 할 수없는 내용이 포함되어 있으면 예외가 발생할 수 있습니다 (예 : 1234
는 성공하지만 123abc
던지기).
C++ 11에서 std::to_string
함수가 정수형에 오버로드되므로 다음과 같은 코드를 사용할 수 있습니다.
int a = 20;
std::string s = to_string(a);
표준은 이들을 sprintf
(int
의 %d
와 같이 제공된 객체 유형과 일치하는 변환 지정자를 사용하여)으로 변환하는 것과 충분한 크기의 버퍼로 변환 한 다음 해당 버퍼의 내용을 std::string
로 만드는 것과 동일한 것으로 정의합니다 .
Boost가 설치된 경우 (필요한 경우) :
#include <boost/lexical_cast.hpp>
int num = 4;
std::string str = boost::lexical_cast<std::string>(num);
스트링 스트림을 사용하는 것이 더 쉬울까요?
#include <sstream>
int x=42; //The integer
string str; //The string
ostringstream temp; //temp as in temporary
temp<<x;
str=temp.str(); //str is temp as string
또는 함수를 만듭니다.
#include <sstream>
string IntToString (int a)
{
ostringstream temp;
temp<<a;
return temp.str();
}
내가 아는 바로는 순수한 C++입니다. 하지만 당신이 언급 한 것을 조금 수정했습니다.
string s = string(itoa(a));
작동해야하며 꽤 짧습니다.
sprintf()
은 형식 변환에 꽤 좋습니다. 그런 다음 1에서와 같이 결과 C 문자열을 C++ 문자열에 지정할 수 있습니다.
첫 번째 포함 :
#include <string>
#include <sstream>
두 번째 방법을 추가합니다 :
template <typename T>
string NumberToString(T pNumber)
{
ostringstream oOStrStream;
oOStrStream << pNumber;
return oOStrStream.str();
}
다음과 같은 방법을 사용하십시오.
NumberToString(69);
또는
int x = 69;
string vStr = NumberToString(x) + " Hello Word!."
C++ 11에서 사용할 수있는 std::to_string
는 Matthieu M.이 제안한 과 같이 사용할 수 있습니다. :
std::to_string(42);
또는 성능이 중요한 경우 (예 : 많은 전환을 수행하는 경우) C++ Format 라이브러리의 fmt::FormatInt
를 사용하여 정수를 std::string
로 변환 할 수 있습니다.
fmt::FormatInt(42).str();
또는 C 문자열 :
fmt::FormatInt f(42);
f.c_str();
후자는 동적 메모리 할당을하지 않으며 Boost Karma 벤치 마크에서 std::to_string
보다 10 배 이상 빠릅니다. 자세한 내용은C++의 문자열 변환에 대한 빠른 정수를 참조하십시오.
std::to_string
와 달리 fmt::FormatInt
에는 C++ 11이 필요하지 않으며 모든 C++ 컴파일러에서 작동합니다.
면책 조항 : 저는 C++ Format 라이브러리의 저자입니다.
숫자 변환에 stringstream 사용은 위험합니다! _
http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/ 여기서 operator<<
가 형식이 지정된 출력을 삽입한다는 것을 나타냅니다.
현재 로케일에 따라 3 자리 이상의 정수가 4 자리수 문자열로 변환되어 추가로 1000 단위 구분 기호가 추가 될 수 있습니다.
예 : int = 1000
는 문자열을 1.001
로 변환 할 수 있습니다. 이로 인해 비교 연산이 전혀 작동하지 않을 수 있습니다.
그래서 나는 강력하게 std::to_string
방법을 사용하는 것이 좋습니다. 그것은 더 쉽고 당신이 기대하는 바를 수행합니다.
C++ 98의 경우 몇 가지 옵션이 있습니다.
boost/lexical_cast
Boost는 C++ 라이브러리의 일부는 아니지만 많은 유용한 라이브러리 확장을 포함합니다.
lexical_cast
함수 템플릿은 텍스트로 표시 될 때 임의 유형과의 일반적인 변환을 지원하기위한 편리하고 일관된 형식을 제공합니다.
- 부스트의 문서
#include "boost/lexical_cast.hpp"
#include <string>
int main() {
int x = 5;
std::string x_str = boost::lexical_cast<std::string>(x);
return 0;
}
런타임에 관해서는 lexical_cast
작업이 첫 번째 변환에서 약 80 마이크로 초 (내 컴퓨터에서) 걸리고, 중복 작업을 수행하면 이후에 상당히 빨라집니다.
itoa
이 함수는 ANSI-C에서 정의되지 않았으며 C++의 일부가 아니지만 일부 컴파일러에서 지원됩니다.
- cplusplus.com
즉, gcc
/g++
은 itoa
을 사용하여 코드를 컴파일 할 수 없습니다.
#include <stdlib.h>
int main() {
int x = 5;
char * x_str = new char[2];
x_str = itoa(x, x_str, 10); // base 10
return 0;
}
보고 할 런타임이 없습니다. Visual Studio가 설치되어 있지 않습니다. 보고 할 수있는itoa
을 (를) 컴파일 할 수 있습니다.
sprintf
sprintf
은 C 문자열에서 작동하는 C 표준 라이브러리 함수이며 완벽하게 유효한 대안입니다.
Printf에서 format이 사용 된 경우 인쇄 될 텍스트와 동일한 문자열을 구성하지만 인쇄되는 대신 내용은 str이 가리키는 버퍼에 C 문자열로 저장됩니다.
- cplusplus.com
#include <stdio.h>
int main() {
int x = 5;
char * x_str = new char[2];
int chars_written = sprintf(x_str, "%d", x);
return 0;
}
stdio.h
헤더가 필요하지 않을 수도 있습니다. 런타임에 관해서는 sprintf
연산은 첫 번째 변환에서 약 40 마이크로 초 (내 컴퓨터에서) 걸리고, 중복으로 완료되면 상당히 가속화됩니다.
stringstream
이것은 정수를 문자열로 또는 그 반대로 변환하는 C++ 라이브러리의 주요 방법입니다. stringstream
과 같은 자매 기능이 ostringstream
과 같이 스트림의 의도 된 사용을 더 제한합니다. ostringstream
을 사용하면 코드 독자에게 <<
연산자 만 사용해야한다는 사실을 알릴 수 있습니다. 이 함수는 정수를 문자열로 변환하는 데 특히 필요합니다. 좀 더 정교한 토론을 위해 이 질문 을보십시오.
#include <sstream>
#include <string>
int main() {
int x = 5;
std::ostringstream stream;
stream << x;
std::string x_str = stream.str();
return 0;
}
런타임에 관해서는 ostringstream
연산은 약 71 마이크로 초 (내 컴퓨터에서) 걸리고 중복 수행되면 속도가 빨라지지만 이전 함수 만큼은 아니지만.
물론 다른 옵션이 있으며,이 중 하나를 자신의 함수로 래핑 할 수도 있습니다. 그러나 이는 인기있는 함수를 분석적으로 보여줍니다.
하나의 구문 적 설탕을 추가하여 스트림 상에 문자열을 작성할 수있게하는 것이 쉽습니다.
#include <string>
#include <sstream>
struct strmake {
std::stringstream s;
template <typename T> strmake& operator << (const T& x) {
s << x; return *this;
}
operator std::string() {return s.str();}
};
이제 << (std::ostream& ..)
에 연산자 strmake()
가 정의되어 있으면 원하는대로 추가하고 std::string
대신 사용할 수 있습니다.
예:
#include <iostream>
int main() {
std::string x =
strmake() << "Current time is " << 5+5 << ":" << 5*5 << " GST";
std::cout << x << std::endl;
}
용도:
#define convertToString(x) #x
int main()
{
convertToString(42); // Returns const char* equivalent of 42
}
C++ 17은 std :: to_chars 를 고성능 로케일 독립적 인 대안으로 제공합니다.
나는 사용한다:
int myint = 0;
long double myLD = 0.0;
string myint_str = static_cast<ostringstream*>( &(ostringstream() << myint) )->str();
string myLD_str = static_cast<ostringstream*>( &(ostringstream() << myLD) )->str();
그것은 내 창문과 리눅스 g ++ 컴파일러에서 작동합니다.
그것은 나를 위해 일한 나의 코드 :
#include <iostream>
using namespace std;
int main()
{
int n=32;
string s=to_string(n);
cout << "string: " + s << endl;
return 0;
}
namespace std
{
inline string to_string(int _Val)
{ // convert long long to string
char _Buf[2 * _MAX_INT_Dig];
snprintf(_Buf, "%d", _Val);
return (string(_Buf));
}
}
이제 to_string(5)
을 사용할 수 있습니다.
#include "stdafx.h"
#include<iostream>
#include<string>
#include<string.h>
std::string intToString(int num);
int main()
{
int integer = 4782151;
std::string integerAsStr = intToString(integer);
std::cout << "integer = " << integer << std::endl;
std::cout << "integerAsStr = " << integerAsStr << std::endl;
return 0;
}
std::string intToString(int num)
{
std::string numAsStr;
while (num)
{
char toInsert = (num % 10) + 48;
numAsStr.insert(0, 1, toInsert);
num /= 10;
}
return numAsStr;
}
여기에 또 다른 쉬운 방법이 있습니다.
char str[100] ;
sprintf(str , "%d" , 101 ) ;
string s = str;
sprintf는 모든 데이터를 필수 형식의 문자열에 삽입하는 잘 알려진 기술입니다.
char * 배열을 세 번째 줄에 표시된대로 문자열로 변환 할 수 있습니다.
string number_to_string(int x){
if(!x) return "0";
string s,s2;
while(x){
s.Push_back(x%10 + '0');
x/=10;
}
reverse(s.begin(),s.end());
return s;
}
char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs,"%d",timeStart.elapsed()/1000);
sprintf(bufMs,"%d",timeStart.elapsed()%1000);
너 왜 그냥 할 수 없어?
int a = 10;
string str = a + '0';
CString
사용 :
int a = 10;
CString strA;
strA.Format("%d", a);
제 생각에는 stringstream을 사용하는 것은 꽤 쉽습니다.
string toString(int n)
{
stringstream ss(n);
ss << n;
return ss.str();
}
int main()
{
int n;
cin>>n;
cout<<toString(n)<<endl;
return 0;
}
"순수한"C++ (C++ 11 등 없음) 사용 :
#include <bits/stdc++.h>
using namespace std;
string to_str(int x) {
ostringstream ss;
ss << x;
return ss.str();
}
int main()
{
int number = 10;
string s = to_str(number);
cout << s << endl;
return 0;
}