C++ 按行读取文件

来源:百度知道 编辑:UC知道 时间:2024/06/09 13:21:51
我有一个txt文件,内容如下
5 31 4 85 12 52 63
54 32 5 63 45 4 3 1 6
4 2 5 3 6 1 8
怎么将这三行数据分别放入三个整型数组中?
用C++语言实现。。。感激不尽~~~

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

double get_length(string filename){
ifstream infile_obj(filename.c_str(),ifstream::in);
double len=0;
if(!infile_obj){
infile_obj.close();
return -1;
}
string t="";
while(!infile_obj.eof()){
infile_obj>>t;
len++;
}
infile_obj.close();
return len;
}

void main(){
string fname;
cin>>fname;
double d;
d=get_length(fname);
cout<<d;
int* p=new int[d];
ifstream myin(fname.c_str());
int i,j=0;
while(!myin.eof()){
myin>>i;
p[j++]=i;
}
j=0;
while(j<d){
if(j%5==0)
cout<<endl;
cout<<p[j]<<" ";
j++;
}
cout<<endl;
}

我没有加换行判断了,我想你也会吧,希望上述代码对你有帮助~

随手写的,没调试过,你试试吧