mad*_*ddy 1 c++ string type-conversion sstream
我正在尝试将任意长度的字符串转换为int,但到目前为止它只适用于有限长度的字符串.代码到目前为止:
long long convertToInt (std::string x){
long long number;
std::istringstream ss(x);
ss >> number;
return number;}
Run Code Online (Sandbox Code Playgroud)
为x=100000000000000000000000001函数返回0.有人能解释为什么吗?谢谢.
该值"100000000000000000000000001"很大以适合long long(或unsigned long long),因此提取失败.
使用numeric_limits以确定您的实现类型的最大值:
#include <limits>
std::cout << std::numeric_limits<unsigned long long>::max() << "\n";
std::cout << std::numeric_limits<long long>::max() << "\n";
std::cout << "100000000000000000000000001\n";
Run Code Online (Sandbox Code Playgroud)
打印:
18446744073709551615 9223372036854775807 100000000000000000000000001
检查提取尝试的结果以确保提取发生:
if (ss >> number)
{
return number;
}
// Report failure.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
135 次 |
| 最近记录: |