본문 바로가기
programming/C 와 C++

<C++> 정수형을 문자열로

by 안중바리 2020. 10. 19.

1. to_string

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

 

 

std::to_string - cppreference.com

(1) (since C++11) (2) (since C++11) (3) (since C++11) (4) (since C++11) (5) (since C++11) (6) (since C++11) (7) (since C++11) (8) (since C++11) (9) (since C++11) Converts a numeric value to std::string. 1) Converts a signed integer to a string with the sam

en.cppreference.com

std::string to_string( int value );

std::string to_string( long value );

std::string to_string( long long value );

std::string to_string( unsigned value );

std::string to_string( unsigned long value );

std::string to_string( unsigned long long value );

std::string to_string( float value );

std::string to_string( double value );

std::string to_string( long double value );

 

같은 이름의 함수지만 매개변수가 다른 함수(메소드)를 오버로딩이라 한다.

to_string 함수는 integer가 값을 아니더라도 문자열로 만들 수 엤게 하기 위하여 오버로딩 방식을 택했을 것이다.

to_string 함수는 string 라이브러리에 포함되어 있는 함수이다.

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

int main() {
	int i = 1234;
	double d = 1234.5687;
	
	cout << "i's type : " << typeid(i).name() << "  ---- convert --->  " << typeid(to_string(i)).name() << '\n';
	cout << "d's type : " << typeid(d).name() << "  ---- convert --->  " << typeid(to_string(d)).name();

	return 0;
}

이렇게 잘 변환 된 것을 볼 수 있습니다.

 

2. sstream(stringstream)

 

다음은 sstream 클래스를 이용한 변환입니다. 정수형에서 문자열로 양 변환이 가능합니다.

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

int main() {
	int i = 1234;
	double d = 1234.56;

	stringstream str_int;
	stringstream str_double;

	str_int << i;
	str_double << d;

	cout << typeid(i).name() << " ---- convert ---> " << typeid(str_int).name() << '\n';
	cout << typeid(d).name() << " ---- convert ---> " << typeid(str_double).name();

	return 0;
}

 

잘 변환이 된 것을 볼 수 있을 것이다.

 

이렇게 수를 문자열로 바꾸는 방법을 소개해드렸습니다. 이 방법 외에도 boost를 사용하거나 다른 방법이 있을 수 있고 스스로 함수를 만들어서 해도 상관은 없습니다.

'programming > C 와 C++' 카테고리의 다른 글

<C++> 문자열을 정수형으로  (0) 2020.10.18