C++ 无法从ifstream读取大整数
我有一个txt文件:C++ 无法从ifstream读取大整数,c++,fstream,C++,Fstream,我有一个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" << s
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;
}
但是,使用以下文件:
1 2 3
结果是:
Vector size is: 0
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();
}
#包括
#包括
int main()
{
std::coutvoid read_输入(const char*文件,std::vector&input)
{
std::iff流(文件);
如果(!f)
{
std::cerrint c;
->无符号长c;
和std::vector
->std::vector
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;
}