![](/img/trans.png)
[英]How to read unsigned int variables from file correctly, using ifstream?
[英]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.