如何用C++从一个TXT文件中逐行读取数据
1个回答
展开全部
//可以用ifstream的getline方法或>>运算符重载来按行读取文本文件,具体看例子。
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
int main(int argc,char* argv[])
{
//将f设置为要按行读取的文本文件名
char f[]="t.txt",buf[1024]={'\0'};
ifstream inf(f,ios_base::in);
string line;
while(!inf.eof())
{
inf.getline(buf,1024);
cout<<buf<<endl;
}
cout<<endl;
inf.close();
inf.open(f,ios_base::in);
while(!inf.eof())
{
inf>>line;
cout<<line<<endl;
}
inf.close();
system("PAUSE");
return EXIT_SUCCESS;
}
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
int main(int argc,char* argv[])
{
//将f设置为要按行读取的文本文件名
char f[]="t.txt",buf[1024]={'\0'};
ifstream inf(f,ios_base::in);
string line;
while(!inf.eof())
{
inf.getline(buf,1024);
cout<<buf<<endl;
}
cout<<endl;
inf.close();
inf.open(f,ios_base::in);
while(!inf.eof())
{
inf>>line;
cout<<line<<endl;
}
inf.close();
system("PAUSE");
return EXIT_SUCCESS;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询