本文主要是介绍C++ stoi函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
stoi函数是C++标准库中的一个函数,用于将字符串转换为整数。
stoi函数的定义如下:
int stoi(const string& str, size_t* idx = 0, int base = 10);
参数说明:
- str:要转换的字符串。
- idx:可选参数,用于存储转换结束的位置,即第一个无效字符的位置。
- base:可选参数,指定转换时使用的进制,默认为10进制。
返回值:
- 返回转换后的整数值。
示例如下:
#include <iostream>
#include <string>
int main() {std::string str = "12345";int num = std::stoi(str);std::cout << num << std::endl; // 输出:12345str = "1010";int binaryNum = std::stoi(str, nullptr, 2);std::cout << binaryNum << std::endl; // 输出:10str = "123abc";size_t idx;int result = std::stoi(str, &idx);std::cout << result << std::endl; // 输出:123std::cout << "Invalid character position: " << idx << std::endl; // 输出:3return 0;
}
运行结果:
通过调用stoi函数将字符串转换为整数。第一个示例将字符串"12345"转换为整数12345,第二个示例将字符串"1010"按二进制转换为整数10。第三个示例中,由于字符串"123abc"中包含无效字符"a",转换结束的位置为3,所以只将前面的数字"123"转换为整数123
这篇关于C++ stoi函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!