본문 바로가기

BE/C++

[C++][형변환] int에서 char*, char*에서 int로 변경하기

인트로

안녕하세요. 오늘은 C++에서 int 에서 char*/char* 에서 int 로 변경하는 방법에 대해서 포스팅하겠습니다.

(형변환) int <-> char* : https://life-with-coding.tistory.com/284

(형변환) int <-> string : https://life-with-coding.tistory.com/283

 

int <-> char* 형변환

1) int 에서 char*로 변경하기

int data = 5;
char temp[2] = "";
itoa(data, temp, 10);

 

그렇지만 itoa를 그냥 쓰게 되면, 다음과 같은 Visual Studio오류가 발생합니다.

오류 C4996 'itoa'

The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _itoa. 

 

위와 같이 오류가 뜨고, itoa에 _를 붙이라고 합니다. 그래서 아래와 같이 붙입니다. 

_itoa(data, temp, 10);

 

'오류 C4996 '_itoa'

This function or variable may be unsafe. Consider using _itoa_s instead. To disable deprecation,
use _CRT_SECURE_NO_WARNINGS.'.

 

위와같은 오류가 뜬다. safe버전을 쓰거나, #define _CRT_SECURE_NO_WARNINGS를 선언하라는 것입니다.

최종적으로, itoa 함수는 아래와 같이 써야합니다. 

_itoa_s(data, temp, 10);

_itoa_s(data, temp, 10);

 

2) char*에서 int로 변경하기

char ch[10] = "200";
int data = atoi(ch);

 

char*에서 int로 변경하는 경우는 atoi함수를 사용하면됩니다.

함수의 원형 : int atoi(const char* cStr);

 

 

이상으로 C++에서 형변환하는 방법에 대해 포스팅을 마칩니다. 

감사합니다 :D