简体   繁体   English

无法从ifstream读取big int

[英]Cannot read big int from ifstream

I have a txt file: 我有一个txt文件:

4286484840 4286419048 4286352998

(They are RGB values.) (它们是RGB值。)

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). 在当今最常见的系统上, int是32位,并且其最大值是2^31-1 ,尽管只能保证是2^15-1 (需要16位)。 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 . 为了保证代表较大的值,可以使用long long unsigned long will do too, but barely. unsigned long也可以,但是几乎没有。 If you need integers of a specific size, I recommend you take a look at the <cstdint> header. 如果需要特定大小的整数,建议您查看<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;
}

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

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