Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Phân tích chuỗi thành int trong C++


Có thể dùng stringstream để phân tích chuỗi thành int. Cần kiểm tra lỗi cho phương pháp này.

Ví dụ (stringstream)

#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;
}

Đầu ra

12345

Từ C++11, có các hàm chuẩn: stoi (string to int), stol (string to long), stoll (string to long long), stoul (string to unsigned long), v.v.

Ví dụ (C++11 stoi)

#include <iostream>
using namespace std;

int main() {
    string s = "12345";
    int x = stoi(s);
    cout << x;
}

Đầu ra

12345