溫馨提示×

c++字符串怎么轉化為數字

c++
小億
318
2023-11-01 16:09:57
欄目: 編程語言

在C++中,可以使用以下方法將字符串轉換為數字:

  1. 使用stoi()函數將字符串轉換為整數。stoi()函數接受一個字符串參數,并返回相應的整數值。
#include <iostream>
#include <string>

int main() {
    std::string str = "123";
    int num = std::stoi(str);
    std::cout << "Converted number: " << num << std::endl;
    return 0;
}
  1. 使用stof()函數將字符串轉換為浮點數。stof()函數接受一個字符串參數,并返回相應的浮點數值。
#include <iostream>
#include <string>

int main() {
    std::string str = "123.45";
    float num = std::stof(str);
    std::cout << "Converted number: " << num << std::endl;
    return 0;
}

需要注意的是,以上方法在轉換過程中只能接受有效的數字字符串,否則會拋出異常。如果需要處理可能包含無效字符的字符串,可以使用更復雜的方法,如使用正則表達式或逐個字符解析等。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女