How to read groups of integers from a file, line by line in C++(如何在 C++ 中逐行读取文件中的整数组)
问题描述
我有一个文本文件,每行一个或多个整数,用空格分隔.我怎样才能用 C++ 以优雅的方式阅读这个?如果我不关心行,我可以使用 cin >>,但重要的是在哪一行整数上.
I have a text file with on every line one or more integers, seperated by a space. How can I in an elegant way read this with C++? If I would not care about the lines I could use cin >>, but it matters on which line integers are.
示例输入:
1213 153 15 155
84 866 89 48
12
12 12 58
12
推荐答案
这取决于您是要逐行还是完整地进行.将整个文件转化为一个整数向量:
It depends on whether you want to do it in a line by line basis or as a full set. For the whole file into a vector of integers:
int main() {
std::vector<int> v( std::istream_iterator<int>(std::cin),
std::istream_iterator<int>() );
}
如果您想在一行一行的基础上进行交易:
If you want to deal in a line per line basis:
int main()
{
std::string line;
std::vector< std::vector<int> > all_integers;
while ( getline( std::cin, line ) ) {
std::istringstream is( line );
all_integers.push_back(
std::vector<int>( std::istream_iterator<int>(is),
std::istream_iterator<int>() ) );
}
}
这篇关于如何在 C++ 中逐行读取文件中的整数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中逐行读取文件中的整数组


- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01