在C++中,将`string`转换为`int`的方法主要有以下几种:
使用`stoi()`函数
`stoi()`是C++11标准库中的函数,用于将字符串转换为整数。它直接接收一个字符串参数并返回一个整数。如果字符串无法转换为整数,`stoi()`会抛出一个`std::invalid_argument`异常。
示例代码:
```cpp
include include int main() { std::string str = "123"; try { int number = std::stoi(str); std::cout << "Converted number: " << number << std::endl; } catch (const std::invalid_argument& e) { std::cerr << "Invalid argument: " << e.what() << std::endl; } return 0; } ``` `istringstream`是C++标准库中的类,用于将字符串解析为输入流,然后从中提取数据。它比`stoi()`更灵活,可以处理包含非数字字符的字符串,并且可以自定义转换。 示例代码: ```cpp include include include int main() { std::string str = "456"; std::istringstream ss(str); int number; ss >> number; if (ss.fail()) { std::cerr << "Conversion failed" << std::endl; } else { std::cout << "Converted number: " << number << std::endl; } return 0; } ``` `atoi()`是C标准库中的函数,用于将字符串转换为整数。它接收一个C风格字符串(即`const char*`)并返回一个整数。如果字符串无法转换为整数,`atoi()`会返回0,并且可能会设置`errno`以指示错误原因。 示例代码: ```cpp include include include int main() { std::string str = "789"; int number = std::atoi(str.c_str()); if (errno == ERANGE) { std::cerr << "Number out of range" << std::endl; } else if (errno == EINVAL) { std::cerr << "Invalid argument" << std::endl; } else { std::cout << "Converted number: " << number << std::endl; } return 0; } ``` 建议 如果字符串格式明确且无非数字字符,使用`stoi()`函数是最简单直接的方法。 如果字符串可能包含非数字字符或需要自定义转换,使用`istringstream`类会更灵活。 如果需要与C代码兼容或处理C风格字符串,可以使用`atoi()`函数,但需要注意其错误处理机制。使用`istringstream`类
使用`atoi()`函数