getline按行读取内容(C++)
•功能:
–从输入流中读入字符,存到string变量
–直到出现以下情况为止:
•读入了文件结束标志
•读到一个新行
•达到字符串的最大长度
–如果getline没有读入字符,将返回false,可用于判断文件是否结束
#include<stdio.h>
#include<string.h>
#define INFO_MAX_SZ 255
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
void readLine()
{
ifstream f("t.txt", ios::in);
string buff;
while(getline(f, buff))
cout << buff << endl;
}
int main()
{
readLine();
return 0;
}
fgets读取行(C)
#include<stdio.h>
#include<string.h>
#define INFO_MAX_SZ 255
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
void fgetsLine()
{
FILE* f = fopen("t.txt", "r");
if(f == NULL)
cout << "打开文件失败" << endl;
char ch[1024];
while(fgets(ch, 1024, f))
{
cout<< ch;
}
}
int main()
{
fgetsLine();
return 0;
}
按字段读取(C++)
#include<stdio.h>
#include<string.h>
#define INFO_MAX_SZ 255
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
void reader()
{
ifstream f("t.txt", ios::in);
if(!f.is_open())
cout << "文件打开失败" << endl;
while(f != NULL)
{
string ch;
f >> ch;
if(ch == "")
break;
cout << ch << endl;
}
}
int main()
{
reader();
return 0;
}