无法从ifstream中读取大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;
}
相关文章:
- 为什么我可以从C++文件中读取 int 值,但不能浮点?
- 通过 char* 缓冲区读取 int 的行为是不同的,无论是正数还是负数
- 从带有 std::ifstream::read() 的文件中读取 int 遍历 char * 二进制数据
- 从 ifstream 读取 int 到 2-D 动态数组
- 使用 c++ 时从二进制文件中读取 int 不正确
- C++ 从文件中读取 int,每个数字用逗号分隔
- 使用iStream从文件中读取int数据
- openssljava到c++读取int问题
- 在 c++ 中从向量中读取 int 值
- 从第 3 位开始读取 int 的最快方法?
- C++读取 int 和字符串,可能同时读取
- 在C++中一次一行地从文本文件中读取int(好的字符,然后转换)时出现问题
- 读取int中的数字并对其进行计数
- 从十六进制数组读取 Int
- 从STDIN读取int时的奇怪行为
- c/c++scanf/cin从多行读取int
- 当循环失败时,当读取int和字符串C++时
- 如何在写入/读取int值时触发函数调用
- 从istream中读取int,检测溢出
- 每行读取int并显示百分比