温馨提示×

c++字符串怎么转化为数字

c++
小亿
99
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