读取空格将数字从文本文件分隔到整数数组 (C++)
Reading space separated numbers from text file to an array of ints (C++)
我需要一些帮助,将文本文件中空格分隔的整数读取到数组。 下面是文本文件的示例:"69 2 189 1876"。 整数的数量是已知的(在本例中为 4)。我尝试了谷歌搜索,但仍然没有找到令人满意的解决方案。这是我第一次做文件 I/O,所以请放轻松。提前致谢:)
只需使用 std::copy
:
#include <algorithm>
#include <fstream>
#include <iterator>
#include <vector>
std::vector<int> array;
std::ifstream stream("filename");
std::copy(std::istream_iterator<int>(stream),
std::istream_iterator<int>(),
std::back_inserter(array));
如果您只想阅读前 N 个,请使用 std::copy_n
而不是 std::copy
。
下面展示了一种可能的方法:
const size_t N = 4;
int a[N] = {};
std::ifstream in( "YourTextFile" );
size_t n = 0;
while ( n < N && in >> a[n] ) ++n;
如果读取值的数量未知,则可以使用标准类 std::vector 代替数组。例如
std::ifstream in( "YourTextFile" );
std::vector<int> v;
int num;
while ( in >> num ) v.push_back( num );
如果要显示文件至少包含矢量中保留的元素数,则可以为矢量保留一些初始内存。例如
v.reserve( 4 );
相关文章:
- 从二进制文件中读取整数数组
- 新的整数数组向右移动?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 从两个 4x64 位整数数组中获取取模
- 字符到整数数组
- 从函数参数 [C++] 复制整数数组
- 指向整数数组和打印总和的指针
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 线程安全整数数组?
- 整数数组中最长的回文
- 在大整数数组中查找子数组
- 查找整数数组中最接近的数字
- 创建<int>对整数数组指针的矢量引用 (C++)
- 整数指针数组的元素是否可以指向整数数组?
- 如何将整数数组相乘得到一个数字?
- 当 map 是一个整数数组并且由 operator[] 创建时,它是否初始化其映射类型
- 将文本文件读入整数数组