atoi 和stoi有什么区别
时间: 2025-06-29 20:08:26 浏览: 2
### C++ 中 `atoi` 和 `stoi` 的区别
#### 参数类型差异
`atoi()` 接受的是 `const char*` 类型的参数,这意味着当传入一个 `std::string` 对象时,需要通过 `.c_str()` 方法将其转换为 C 风格字符串[^1]。相对而言,`stoi()` 可以直接接受 `const std::string&` 类型的参数,无需额外转换操作。
#### 范围检查机制
`stoi()` 函数内置了数值范围验证逻辑,在遇到超出目标数据类型表示范围的情况时会抛出异常(通常是 `std::out_of_range`),这有助于程序及时发现并处理潜在错误[^2]。相比之下,`atoi()` 不执行此类检查,对于越界的输入只会简单地返回最大或最小可能值而不提示任何警告信息。
#### 错误输入行为
面对非法字符序列(即无法解析成有效整数的部分),两者表现也有所不同。具体来说,`atoi()` 在这种情况下默认返回零值;而 `stoi()` 则更加严格,一旦检测到不可识别的内容就会立即终止解析过程并向调用者报告异常事件(如 `std::invalid_argument`)。
```cpp
#include <iostream>
#include <string>
#include <cstdlib> // For atoi()
#include <stdexcept>
void demonstrateAtoiStoiDifferences() {
try {
std::string validNumberStr = "123";
std::string invalidNumberStr = "abc";
int resultUsingAtoiValid = atoi(validNumberStr.c_str());
int resultUsingStoiValid = stoi(validNumberStr);
std::cout << "Converting '" << validNumberStr << "' with atoi(): " << resultUsingAtoiValid << "\n"
<< "Converting '" << validNumberStr << "' with stoi(): " << resultUsingStoiValid << '\n';
// This will cause different behaviors between the two functions.
int resultUsingAtoiInvalid = atoi(invalidNumberStr.c_str());
std::cout << "Converting '" << invalidNumberStr << "' with atoi(): " << resultUsingAtoiInvalid << '\n';
// The following line would throw an exception when using stoi().
// Uncomment to see how it behaves differently from atoi():
// int resultUsingStoiInvalid = stoi(invalidNumberStr);
} catch (const std::exception &e) {
std::cerr << e.what();
}
}
```
阅读全文
相关推荐


















