Programming/C/C++

문자열과 숫자형 변환

유기농코더 2011. 1. 26. 23:41

가끔 문자열과 숫자열을 서로서로 바꿔서 사용하거나 문자열에 숫자를 집어넣어서 표기 해야 하는 때가 종종(꽤 많이..ㅋ) 발생하게 되죠?

한동안 많이 버벅 였지만, 다른 사람들은 버벅이지 말라고 정리를 하게 되었습니다ㅎㅅㅎ

   

  • C Style
    	
    	#include <stdio.h>
    	#include <stdlib.h>
    	 
    	int main(){
    		/* 문자 → 숫자 */
    		char *testChar1 = "12345";
    		char *testChar2 = "abcde";
    		int testInt1;
    		int testInt2;
    		testInt1 = atoi(testChar1);
    		testInt2 = atoi(testChar2);
    	 
    		printf("문자 : %s\n", testChar1);
    		printf("숫자: %d\n", testInt1);
    	 
    		printf("\n");
    	 
    		printf("문자 : %s\n", testChar2);
    		printf("숫자 : %d\n", testInt2);
    	 
    		printf("\n");
    	 
    	 
    		/* 숫자 → 문자 */
    		char *testChar3 = (char*)malloc(200);
    		int testInt3 = 19841219;
    	 
    		sprintf(testChar3, "%d", testInt3);
    	 
    		printf("숫자 : %d\n", testInt3);
    		printf("문자 : %s\n", testChar3);
    	 
    		printf("\n");
    	 
    		free(testChar3);
    	 
    		char *testChar4 = (char*)malloc(200);
    		int testInt4 = 123;
    	 
    		sprintf(testChar4, "%s_%d.txt", "hello", testInt4);
    	 
    		printf("응용 : %s\n", testChar4);
    	 
    		free(testChar4);
    		
    		system("pause");
    		return 0;
    
    }
    
  1. 문자 → 숫자 로 바꾸려면 atoi() 함수를 사용 하면 됩니다.
  2. 단, 알파벳으로 시작되는 문자는 변경되지 않습니다.
  3. 단, 숫자+알파벳의 문자열을 숫자만 변경 해줍니다.
  4. 숫자 → 문자는 itoa 쓰지 마시고 sprintf()를 사용하시면 됩니다.

       

   

  • C++ Style
    	#include <iostream>
    	#include <sstream>
    	#include <string>
    	 
    	int main(){
    		/* 문자 → 숫자 */
    		std::stringstream ss1;
    		std::string testString1 = "12345";
    		std::string testString2 = "abcde";
    	 
    		int testInt1;
    		int testInt2;
    	 
    		ss1 << testString1;
    		ss1 >> testInt1;
    		ss1 << testString2;
    		ss1 >> testInt2;
    	 
    		std::cout << "문자 : " << testString1 << std::endl;
    		std::cout << "숫자 : " << testInt1 << std::endl;
    	 
    		std::cout << std::endl;
    	 
    		std::cout << "문자 : " << testString2 << std::endl;
    		std::cout << "숫자 : " << testInt2 << std::endl;
    	 
    		std::cout << std::endl;
    	 
    		/* 숫자 → 문자 */
    		std::stringstream ss2;
    		std::string testString3;
    		int testInt3 = 19841219;
    	 
    		ss2 << testInt3;
    		ss2 >> testString3;
    	 
    		std::cout << "숫자 : " << testInt3 << std::endl;
    		std::cout << "문자 : " << testString3 << std::endl;
    	 
    		system("pause");
    		exit(EXIT_SUCCESS);
    
    }
    

    C와는 다르게 stringstream이라는 매개체를 통해 서로서로 바꿀 수 있다.