简体   繁体   English

将字符串转换为十六进制抛出错误:'std::out_of_range'

[英]Converting String to Hex Throws Error: 'std::out_of_range'

I have a really simple program that converts a hex string to it's int value.我有一个非常简单的程序,可以将十六进制字符串转换为其 int 值。 The code seems fine, but it throws a runtime error:代码看起来不错,但会引发运行时错误:

terminate called after throwing an instance of 'std::out_of_range' what(): stoi在抛出 'std::out_of_range' what(): stoi 实例后终止调用

Here is the code where the error is being caused:这是导致错误的代码:

int dump[4];
string hexCodes[4] = {"fffc0000", "ff0cd044", "ff0000fc", "ff000000"};
for (int i = 0; i < 4; i++)
{
    dump[i] = 0;
    dump[i] = stoi(hexCodes[i], 0, 16);
    cout << dump[i] << endl;
}

I have tried reading a couple of pages such as this .我试过阅读这样的几页。 I still can't find anything that relates to my issue.我仍然找不到与我的问题相关的任何内容。 What am I doing wrong that is causing this error?导致此错误的我做错了什么?

stoi will throw out_of_range if the value is not in the range that int can represent.如果值不在int可以表示的范围内, stoi将抛出out_of_range The number 0xfffc0000 (4294705152) is not in that range for a 32-bit int as it is greater than 2^31-1 (2147483647).数字0xfffc0000 (4294705152) 不在 32 位int的范围内,因为它大于 2^31-1 (2147483647)。 So throwing the exception is precisely what it must do.所以抛出异常正是它必须做的。

unsigned would work, but there is no stou , so use stoul . unsigned可以,但是没有stou ,所以使用stoul You then probably want to use unsigned dump[4] since you know the value can be represented by an unsigned int .然后您可能想使用unsigned dump[4]因为您知道该值可以由unsigned int表示。 (Again, as long as they are 32 bits on your system. uint32_t might be safer.) As a bonus, this will ensure that cout << dump[i] prints out 4294705152 as desired. (同样,只要它们在您的系统上是 32 位的uint32_t可能更安全。)作为奖励,这将确保cout << dump[i]根据需要打印出4294705152

(If you switch to stoul but keep dump as an array of int , the value will be converted to int by the assignment. Under C++20, and for most common systems under earlier C++ standards, the conversion will "wrap around" to -262144 , and outputting dump[i] with << will print it out just that way, as a signed integer with a minus sign. So that doesn't seem to be what you want.) (如果您切换到stoul但将dump保留为int的数组,则该值将通过赋值转换为int 。在 C++20 下,对于早期 C++ 标准下的大多数常见系统,转换将“环绕”到-262144 ,并使用<<输出dump[i]将以这种方式打印出来,作为带负号的签名 integer。所以这似乎不是你想要的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM