如何用c++来进行读txt里面的某行#include iostream#include fstream#include stringusing namespace
如何用c++来进行读txt里面的某行
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
{
int a[5][5];
int t=0;
for(int i=0;i<2;i++)
{
cout<<"i="<<i<<endl;
t++;
for(int j=0;j<2;j++)
{
cin>>a[i][j];
}
}
/*for(i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
cout<<a[i][j];
cout<<endl;
}
}
*/
ofstream ofs("b.txt",ios::app);
for(int k=0;k<t;k++)
{
for(int l=0;l<t;l++)
{
ofs<<a[k][l]<<endl;
}
}
ifstream ifs("b.txt");
if(!ifs)
{
cout<<"文件打开失败!";
return;
}
char ch[100];
while (!ifs.eof())
{
ifs.getline(ch,100);
cout<<ch<<endl;
}
}
[解决办法]
你可以读文件的每一行,然后只处理需要的那行
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
{
int a[5][5];
int t=0;
for(int i=0;i<2;i++)
{
cout<<"i="<<i<<endl;
t++;
for(int j=0;j<2;j++)
{
cin>>a[i][j];
}
}
ofstream ofs("b.txt",ios::app);
for(int k=0;k<t;k++)
{
for(int l=0;l<t;l++)
{
ofs<<a[k][l]<<endl;
}
}
ifstream ifs("b.txt");
if(!ifs)
{
cout<<"文件打开失败!";
return;
}
char ch[100];
int n=1;
while (!ifs.eof())
{
ifs.getline(ch,100);
if (n==2)//处理所需的行数
{
cout<<ch<<endl;
}
++n;
}
}
另外也可以用ignore()函数忽略掉不需要的行数不读。
[解决办法]
要用fseek
必须用fopen打开文件获得文件指针fp
这个楼主网上搜下就可以了,很多的
