我有一个文本文件,每行一个或多个整数,用空格分隔.我怎样才能用 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++ 中逐行读取文件中的整数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!