您的位置:首页 > 编程语言 > C语言/C++

IO

2015-12-22 22:41 387 查看

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言