[C++] char 자료형에서 string 자료형으로 변환하는 법
https://www.techiedelight.com/convert-char-to-string-cpp/
10 ways to convert a char to a string in C++ - Techie Delight
In this post, we will discuss various methods to convert a char to a string in C++. Simple solution would be to use string class fill constructor string (size_t n, char c); which fills the string with n copies of character c. Another good alternative is to
www.techiedelight.com
좋은 글이 있어서 소개해줄려고 한다. 위는 char 자료형에서 string 자료형으로 변환하는 10가지 형태이다.
char 자료형에, to_string을 사용하면 정수 값을 무조건 반환한다.
C++ 레퍼런스에서 가져온 이미지인데, numerical value를 string 자료형으로 전환한다고 되어 있다. 따라서, 문자형태를 to_string의 값으로 들어가지 않는다. 자동 형변환에 의해 char형은 int형으로 변환될 것이므로, 우리가 원하는 문자 형태를 문자열로 변환하지 못한다.
위의 10가지 변환 방법 중에서 괜찮아보이는 것 하나를 추천하겠다.
#include <iostream>
#include <string>
int main()
{
char c = 'A';
// using std::string::operator+=
std::string s;
s += c;
std::cout << s << '\n';
return 0;
}
위의 형태가 가장 간단하고 설명하기도 쉽다. s는 NULL이지만, string 자료형이므로 \0 형태를 띄고 있다. += 연산은 insert 연산과 동일하기 때문에, 최종적으로 문자열 형태인 A\0가 된다.