วิธีที่ 1: ใช้ stringstream (C++98/03)
#include <iostream>
#include <sstream>
using namespace std;
int str_to_int(const string &str) {
stringstream ss(str);
int num;
ss >> num;
return num;
}
int main() {
string s = "12345";
int x = str_to_int(s);
cout << x;
}
ผลลัพธ์
12345
ต้องทำ error checking เอง (เช่น ตรวจสอบว่า ss.fail() หรือไม่)
วิธีที่ 2: ใช้ฟังก์ชันมาตรฐาน C++11 (แนะนำ)
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "12345";
int x = stoi(s); // string to int
// long y = stol(s); // string to long
// long long z = stoll(s); // string to long long
cout << x;
}
ผลลัพธ์
12345
C++11 เพิ่มฟังก์ชัน: stoi, stol, stoll, stoul, stoull, stof, stod, stold 拋出 exception หากแปลงไม่ได้ (invalid_argument, out_of_range)