gpt4 book ai didi

c++ - 无法从 ifstream 读取大整数

转载 作者:行者123 更新时间:2023-11-30 04:11:35 25 4
gpt4 key购买 nike

我有一个 txt 文件:

4286484840 4286419048 4286352998

(它们是 RGB 值。)

我想将它们存储在一个 vector 中。

void read_input(const char* file, std::vector<int>& input)
{
std::ifstream f(file);
if (!f)
{
std::cerr << file << "Read error" << std::endl;
exit(1);
}

int c;
while (f >> c)
{
std::cout << c << std::endl;
input.push_back(c);
}

std::cout << "Vector size is: " << input.size() << std::endl;
}

结果是:

Vector size is: 0

但是对于以下文件:

1 2 3

结果是:

1
2
3
Vector size is: 3

第一个文件有什么问题?数字太大了吗?

最佳答案

是的,数字可能太大了。在当今最常见的系统上,int为32位,最大值为2^31-1 , 虽然它只能保证是 2^15-1 (需要 16 位)。您可以通过以下方式检查您的限制:

#include <limits>
#include <iostream>

int main()
{
std::cout << std::numeric_limits<int>::max();
}

为了保证大值的表示,您可以使用 long long . unsigned long也会做,但几乎没有。如果您需要特定大小的整数,我建议您查看 <cstdint> 标题。

关于c++ - 无法从 ifstream 读取大整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20179219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com