c++ string zhuan int
时间: 2023-10-24 07:01:35 浏览: 143
引用中的代码演示了将string转换为int的方法。可以使用stof函数将string转换为float,然后使用round函数将float四舍五入为最接近的整数,再使用to_string函数将int转换为string。以下是一个示例代码:
```
#include <iostream>
#include <string>
#include <cmath>
std::string strToInt(const std::string& str) {
float floatNum;
try {
floatNum = std::stof(str);
} catch(const std::exception&) {
// 处理异常
}
int intNum = std::round(floatNum);
std::string strNum = std::to_string(intNum);
return strNum;
}
int main() {
std::string str = "-0.898";
std::string result = strToInt(str);
std::cout << result << std::endl;
return 0;
}
```
这段代码首先将string转换为float类型,然后使用round函数将float四舍五入为最接近的整数,再使用to_string函数将int转换为string。最后,代码会打印出转换后的整数字符串。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [C++ 基础类型转换(string, wstring,int, hex)](https://blog.csdn.net/Y_jay/article/details/88898542)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [C++:基础记录:string和整数相互转换](https://blog.csdn.net/u013620306/article/details/128885054)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文