[c++] C++에서의 문자열을 숫자로 변환하는 방법
먼저, std::stoi
함수를 사용하여 문자열을 정수로 변환하는 방법은 다음과 같습니다.
#include <iostream>
#include <string>
int main() {
std::string numberString = "12345";
int number = std::stoi(numberString);
std::cout << "Converted number: " << number << std::endl;
return 0;
}
위의 예제에서는 std::stoi
함수를 사용하여 numberString
문자열을 정수로 변환하고, 변환된 숫자를 출력하고 있습니다.
다음으로, std::stof
함수를 사용하여 문자열을 부동 소수점 숫자로 변환하는 방법은 다음과 같습니다.
#include <iostream>
#include <string>
int main() {
std::string numberString = "123.45";
float number = std::stof(numberString);
std::cout << "Converted number: " << number << std::endl;
return 0;
}
위의 예제에서는 std::stof
함수를 사용하여 numberString
문자열을 부동 소수점 숫자로 변환하고, 변환된 숫자를 출력하고 있습니다.
이와 같이 C++에서는 std::stoi
함수와 std::stof
함수를 사용하여 문자열을 숫자로 변환할 수 있습니다.