아이공의 AI 공부 도전기

[C++] int를 string으로, string을 int로 변경하는 법(atoi, itoa, stringstream)

 

     

 

1. atoi, itoa

C++에서 atio, itoa를 사용하기 위해서는 stdlib.h을 선언해야합니다.

atoi를 기억하기 쉽게 하기 위해 영어로 풀면 alphabet to integer 알파벳에서 정수로라는 의미입니다.

itoa 역시 마찬가지로 영어로 풀면 integer to alphabet 알파벳에서 정수로라는 의미입니다.

 

1) atoi

int atoi (const char *str)

str : 어떤 문자열을 정수로 나타낼 것인지

를 설정합니다.

 

물론 atof, atol, atoll과 같이 double 형식, long 형식, long long 형식으로도 변환이 가능합니다.

 

2) itoa

char *itoa(int value, char *str, int radix)

value : 어떤 정수 값을 변환시킬 것인지

str : 어떤 문자열에 변환할 것인지

radix : 몇 진수로 진행할 것인지

를 설정합니다.

 

https://www.cplusplus.com/reference/cstdlib/itoa/

 

itoa - C++ Reference

function itoa char * itoa ( int value, char * str, int base ); Convert integer to string (non-standard function) Converts an integer value to a null-terminated string using the specified base and stores the result in the array given by str param

www.cplusplus.com

 

예시) 

 

#include <iostream>
#include <typeinfo>
#include <stdlib.h>

using namespace std;
int main() {    
	int n = 2021;
	char tmp[100];
	// type of n is i and number is 2021
	cout << "type of n is " << typeid(n).name() << " and number is " << n << endl;
	
	itoa(n, tmp, 10);
	// type of tmp is A100_c and char is 2021
	cout << "type of tmp is " << typeid(tmp).name() << " and char is " << tmp << endl;	
		
	int t = atoi(tmp);
	// type of t is i and char is 2021
	cout << "type of t is " << typeid(t).name() << " and char is " << t << endl;		
}

 

2. stringstream

sstream 헤더를 포함해야한다. int를 string으로 바꾸는데 활용된다.

 

#include <iostream>
#include <typeinfo>
#include <string>
#include <sstream>

using namespace std;
int main() {    
	int n = 2021;	
	
	// type of n is i and number is 2021
	cout << "type of n is " << typeid(n).name() << " and number is " << n << endl;
	
	stringstream s;
	s << n;
	string str = s.str();
	
	// type of str is Ss and string is 2021
	cout << "type of str is " << typeid(str).name() << " and string is " << str << endl;					
}

 

to_string, sprintf, snprintf 방식 또한 있으나 추후 다룰 예정

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading