1. ASCII 값을 이용한 변환
- 문자 '1'의 ASCII 값은 49입니다.
따라서, 문자 '1'에서 '0'의 ASCII 값을 빼면 정수 1을 얻을 수 있습니다.
#include <iostream>
int main() {
char ch = '1';
int num = ch - '0';
std::cout << num << std::endl;
return 0;
}
2. std::atoi 함수를 사용
std::atoi 함수는 C 문자열을 정수로 변환하는 함수입니다.
문자 하나를 정수로 변환할 때는 이 함수를 사용할 수 있습니다.
#include <iostream>
#include <cstdlib>
int main() {
char ch = '1';
int num = std::atoi(&ch);
std::cout << num << std::endl;
return 0;
}
#include <iostream>
#include <cstdlib>
int main() {
const char* str = "123";
int num = std::atoi(str);
std::cout << num << std::endl;
return 0;
}
3. std::stringstream 을 사용
std::stringstream을 사용하면 문자열을 정수로 쉽게 변환할 수 있습니다.
#include <iostream>
#include <sstream>
int main() {
char ch = '1';
std::stringstream ss;
ss << ch;
int num;
ss >> num;
std::cout << num << std::endl;
return 0;
}
#include <iostream>
#include <sstream>
int main() {
std::string str = "123";
std::stringstream ss(str);
int num;
ss >> num;
std::cout << num << std::endl;
return 0;
}
4. std::stoi 함수를 사용
std::stoi 함수는 C++11부터 사용할 수 있는 문자열을 정수로 변환하는 함수입니다.
#include <iostream>
#include <string>
int main() {
char ch = '1';
int num = std::stoi(std::string(1, ch));
std::cout << num << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str = "123";
int num = std::stoi(str);
std::cout << num << std::endl;
return 0;
}
결론
- 0~9:
ASCII 값을 이용한 변환 이용
- 10 이상:
std::stoi 함수를 사용
만약 입력 문자열이 한 자리일 수도 있고 여러 자리일 수도 있는 상황이라면, 이를 처리하는 일반화된 함수를 작성할 수도 있습니다:
#include <iostream>
#include <string>
int stringToInt(const std::string& str) {
if (str.length() == 1) {
return str[0] - '0';
} else {
return std::stoi(str);
}
}
int main() {
std::string singleDigit = "7";
std::string multipleDigits = "12345";
std::cout << stringToInt(singleDigit) << std::endl;
std::cout << stringToInt(multipleDigits) << std::endl;
return 0;
}