无法从ifstream中读取大int

Cannot read big int from ifstream

本文关键字:读取 int ifstream      更新时间:2023-10-16

我有一个txt文件:

4286484840 4286419048 4286352998

(它们是RGB值。)

我想把它们存储在一个向量中。

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 longunsigned long也会这么做,但几乎不会。如果您需要特定大小的整数,我建议您查看<cstdint>标头。

void read_input(const char* file, std::vector<unsigned long 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;
}