#include <iostream>
using namespace std;
int main() {
char grade = 'B';
cout << "I scored a: " << grade;
return 0;
}
출력:
문자의 ASCII 값 출력
char는 본질적으로 정수이므로 int로 캐스팅하여 ASCII 코드를 드러낼 수 있습니다.
예제 2: 사용자 입력 및 ASCII 출력
#include <iostream>
using namespace std;
int main() {
char ch;
cout << "Enter any character: ";
cin >> ch;
cout << "The ASCII Value of " << ch << " is " << int(ch);
return 0;
}
출력:
ASCII 코드에서 문자 출력
정수 리터럴을 char 변수에 할당하면 컴파일러는 그 정수를 ASCII 코드로 해석하고 해당 문자를 저장합니다.
예제 3: ASCII에서 char 변환
#include <iostream>
using namespace std;
int main() {
char x = 64, y = 66, z = 71;
cout << x << y << z;
return 0;
}
출력:
사용자로부터 문자 읽기
추출 연산자 >>는 입력된 첫 번째 공백이 아닌 문자만 읽습니다. 이후 문자들은 읽을 때까지 입력 버퍼에 남습니다.
예제 4: 두 문자 읽기
#include <iostream>
using namespace std;
int main() {
cout << "Type a sequence of characters: ";
char ch;
cin >> ch;
cout << "The ASCII code of " << ch << " is " << int(ch) << '\n';
cin >> ch;
cout << "The ASCII code of " << ch << " is " << int(ch) << '\n';
return 0;
}
출력:
문자를 문자열로 변환
단일 문자를 std::string으로 변환하는 여러 기법이 있습니다. 가장 일반적인 접근법들을 소개합니다.
#1 – 문자열 생성자 사용
string st(1, 'C');
이 코드는 길이 1, 문자 'C'를 포함하는 문자열을 생성합니다.
예제 5
#include <iostream>
#include <string>
using namespace std;
int main() {
string st(1, 'C');
cout << "The resulting string is : " << st;
return 0;
}
출력:
#2 – 오버로드된 = 및 += 연산자 사용
문자를 문자열에 직접 대입하거나 추가하는 것은 간결하고 읽기 쉽습니다.
예제 6
#include <iostream>
#include <string>
using namespace std;
int main() {
string st;
char b = 'B';
st = 'A';
st += b;
cout << "The resulting string is : " << st;
return 0;
}
출력:
#3 – 문자열 멤버 함수 사용
push_back(char) – 끝에 문자 추가
append(size_t, char) – 문자 여러 복사본 추가
assign(size_t, char) – 문자 여러 복사본으로 문자열 교체
insert(size_t, size_t, char) – 지정된 위치에 문자 삽입
예제 7
#include <iostream>
#include <string>
using namespace std;
int main() {
string st;
st.push_back('A');
cout << "push_back A returns : " << st << endl;
st = "";
st.append(1, 'C');
cout << "append C returns : " << st << endl;
st = "";
st.assign(1, 'D');
cout << "assign D returns : " << st << endl;
st.insert(0, 1, 'E');
cout << "insert single character returns : " << st << endl;
return 0;
}
출력:
#4 – std::stringstream 사용
스트림 연산자는 char에 대해 오버로드되어 있어 문자열로 쉽게 변환 가능합니다.
예제 8
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string st;
stringstream myst;
myst << 'A';
myst >> st;
cout << "The conversion of the single character returns the string: " << st;
return 0;
}