C++ stoi 在转换 int 时抛出 out_of_range

问题描述 投票:0回答:1

我正在解析这样的 CSV 文件:

while (std::getline(iss, value, ',')) {
            cout << col << " " << value << endl;
            switch (col) {
                case 0: customer.id = std::stoi(value); break;

它会停在第一个值处。 在我的控制台中我有这个:

0 3222947947

所以

col
= 0 和
value
= 3222947947。知道为什么
std::stoi(value)
会抛出错误
std::out_of_range
那么吗?

c++
1个回答
3
投票

3222947947 -> 3,222,947,947。超过30亿。

当前标准的32位

int
仅在22亿左右有效。所以如果程序说该值超出范围我会相信。

如果 3222947947 在您的输入集中有效,您需要使用更大的整数(

long long
int64_t
并使用
std::stoll
进行转换)或无符号整数(
unsigned int
uint32_t
并进行转换)与
std::stoul
)如果负数不在
customer.id
的有效输入集中。

© www.soinside.com 2019 - 2024. All rights reserved.