簡體   English   中英

無法從ifstream讀取big int

[英]Cannot read big int from ifstream

我有一個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 long unsigned 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM