C++字符串转数字



在C++中,你可以使用std::stoistd::stolstd::stollstd::stofstd::stoldstd::stol_error函数将字符串转换为各种类型的数字。

  1. 字符串到整数(使用 std::stoi):

#include <string>  
#include <iostream>  
  
int main() {  
    std::string str = "123";  
    int num = std::stoi(str);  
    std::cout << num << std::endl;  // 输出:123  
    return 0;  
}
  1. 字符串到长整数(使用 std::stol 或 std::stoll):

#include <string>  
#include <iostream>  
  
int main() {  
    std::string str = "1234567890";  
    long int num = std::stol(str);  // 对于长整数  
    std::cout << num << std::endl;  // 输出:1234567890  
    return 0;  
}

或者

#include <string>  
#include <iostream>  
  
int main() {  
    std::string str = "1234567890";  
    long long int num = std::stoll(str);  // 对于长长整数  
    std::cout << num << std::endl;  // 输出:1234567890  
    return 0;  
}

字符串到浮点数(使用 std::stof 或 std::stod 或 std::stold

#include <string>  
#include <iostream>  
  
int main() {  
    std::string str = "123.45";  
    float num = std::stof(str);  // 对于浮点数  
    std::cout << num << std::endl;  // 输出:123.450000  
    return 0;  
}

或者

#include <string>  
#include <iostream>  
  
int main() {  
    std::string str = "123.45";  
    double num = std::stod(str);  // 对于双精度浮点数  
    std::cout << num << std::endl;  // 输出:123.450000  
    return 0;  
}

或者对于长双精度浮点数:

#include <string>  
#include <iostream>  
  
int main() {  
    std::string str = "123.45";  
    long double num = std::stold(str);  // 对于长双精度浮点数  
    std::cout << num << std::endl;  // 输出:123.450000 (具体值可能因实现而异)  
    return 0;  
}