이 자습서에서는 C/C++에서 문자열을 숫자로 변환하는 방법을 이해하는 프로그램에 대해 설명합니다.
C/C++는 문자열을 숫자로 변환하는 두 가지 방법을 제공합니다.
예시
sscanf() 사용
#include<stdio.h>
int main(){
const char *str = "12345";
int x;
sscanf(str, "%d", &x);
printf("\nThe value of x : %d", x);
return 0;
} 출력
The value of x : 12345
stoi() 사용
#include <iostream>
#include <string>
using namespace std;
int main(){
string str1 = "45";
string str2 = "3.14159";
string str3 = "31337 geek";
int myint1 = stoi(str1);
int myint2 = stoi(str2);
int myint3 = stoi(str3);
cout << "stoi(\"" << str1 << "\") is " << myint1 << '\n';
cout << "stoi(\"" << str2 << "\") is "<< myint2 << '\n';
cout << "stoi(\"" << str3 << "\") is "<< myint3 << '\n';
return 0;
} 출력
stoi("45") is 45
stoi("3.14159") is 3
stoi("31337 geek") is 31337