简体   繁体   中英

Cannot read big int from ifstream

I have a txt file:

4286484840 4286419048 4286352998

(They are RGB values.)

I would like to store them in a 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;
}

The result is:

Vector size is: 0

However with the following file:

1 2 3

The result is:

1
2
3
Vector size is: 3

What is wrong with the first file? Are the numbers too big?

Yes, the numbers are likely too big. On the most common systems nowadays, int is 32 bits, and its max value is 2^31-1 , although it's only guaranteed to be 2^15-1 (requiring 16 bits). You can check your limits with:

#include <limits>
#include <iostream>

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

In order to guarantee representation for values that large, you can use long long . unsigned long will do too, but barely. If you need integers of a specific size, I recommend you take a look at the <cstdint> header.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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