我尝试使用:
std::string s = "-150";
unsigned int a = atoi(s.c_str());
std::cout << a;
和
std::string s = "-150";
std::istringstream reader(s);
unsigned int a;
reader >> a;
std::cout << a;
我总是得到 4294967146
。我知道它是 U_INT_MAX - 150
。
如果无法转换数字,导致输入数据无效,我怎么会出错?
或者(至少)自动转换为 150
。
附言
我想找到一种无需对字符串进行操作的方法。
最佳答案
您希望输入一个数字,并希望检查它是否适合unsigned int
,然后这样做。将字符串转换为数字的通用数据类型(有符号、 float 、大空间 -> double)并检查它是否可以在不丢失精度的情况下转换为您想要的类型。
你想要一个没有符号的整数,所以你的数字必须是正数,在给定的范围内(目前参见 std::numeric_limits )并且没有小数部分。
关于c++ - 在 C++ 中将字符串转换为无符号数的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35895208/