คุณสามารถใช้สตรีมสตริงเพื่อแยกวิเคราะห์ int ใน c++ เป็น int คุณต้องทำการตรวจสอบข้อผิดพลาดในวิธีนี้
ตัวอย่าง
#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
ใน C++11 ใหม่ มีฟังก์ชันสำหรับสิ่งนั้น:stoi(string to int), stol(string to long), stoll(string to long long), stoul(string to unsigned long) , ฯลฯ
ตัวอย่าง
คุณสามารถใช้ฟังก์ชันเหล่านี้ได้ดังนี้ -
#include<iostream>
using namespace std;
int main() {
string s = "12345";
int x = stoi(s);
cout << x;
} ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ -
12345