如何从一个文件中逐行读取整数的组,在C ++中 [英] How to read groups of integers from a file, line by line in C++
本文介绍了如何从一个文件中逐行读取整数的组,在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文本文件,每行有一个或多个整数,由空格分隔。我怎么能以优雅的方式用C ++读这个?
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>() );
}
如果要按行处理行:
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 ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文