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++ 中逐行读取文件中的整数组
				
        
 
            
        基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 常量变量在标题中不起作用 2021-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				