读取空格将数字从文本文件分隔到整数数组 (C++)

Reading space separated numbers from text file to an array of ints (C++)

本文关键字:整数 数组 C++ 分隔 文件 空格 数字 文本 读取      更新时间:2023-10-16

我需要一些帮助,将文本文件中空格分隔的整数读取到数组。 下面是文本文件的示例:"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 );