<언어>/[C++]

[C++] Type Conversion 정리

콜리브리 2020. 12. 7. 00:57

std::string ↔ C-style char* string

1. C++ String to C-style char*

string a = "I wanna go to bed";

// 방법 1) 기존 String 사용 (Simple)
char *str = &a[0];

// 방법 2) Null-terminated; 길이가 정해져있을때 - strcpy
char ch[100];
strcpy(ch, a.c_str()); // std::string.c_str()
cout<<ch<<endl;

// 방법 3) Null-terminated; 길이 모를때 - vector 사용
std::vector<char> chars(a.c_str(), a.c_str() + a.size() + 1u);
// use &chars[0] as a char*

     방법 1) &str[0] (가장 간단)
stackoverflow.com/questions/7352099/stdstring-to-char/7352131

     방법 2 ) Null-terminated 표현 유지; strcpy로 ch변수에 변환값 저장 혹은 벡터 사용

      * c_str는 string변수를 const char* 로 변환

      

 

2. char* to String

char ch2[100] = {"Oh my god"};
string str(ch2);

cout <<str<<endl;

      std::string constructor에 C-style char* 넣기

 

출저: danco.tistory.com/69?category=725013 [C++ 문법] string to char, char to string 변환

Also see : stackoverflow.com/questions/13217944/c-how-do-i-convert-string-to-char/13218094


std::string ↔ Int

1. String to Int

stoi (std::string), atoi (const char * ; Null-term strings)

 

2. Int to String

to_string

혹은

std::ostringstream os;
os << number;
std::string number_string = os.str();

char ↔ Int

char c = 'a'; 
std::cout << static_cast<int>(c) << std::endl; // prints 97, not 'a'

int i = 49; 
std::cout << static_cast<char>(i) << std::endl; // prints '1'

 

출처: https://boycoding.tistory.com/177?category=1008283 [소년코딩]

 

주의!) int와 char를 서로 캐스팅 해도, 결국 숫자로 나타나는 데이터는 동일;

즉, 1을 그냥 char 변환하면 whitespace 나옴; '1'로 바꾸려면 아래 연산 활용

숫자를 그대로 char로 옮길 때 혹은 그 반대; '0'을 더하든가 빼준다
1 + '0' = '1' (char)
'1' - '0' = 1 (int)