C++语言学习记录-30:使用ifstream中的几个成员函数

get()函数

get函数的作用是读取该类的对象的一个字符并且将该值作为调用函数的返回值。调用get函数时,get函数会自动向后读取下一个字符,直到遇到文件结束符,则返回EOF作为函数的结束

#include<iostream>
using namespace std;
#include<string>
#include<fstream>
int main()
{
    
    
	ifstream infile;
	char value;
	infile.open("a.txt");
	if (infile.is_open())
	{
    
    
		while (infile.get(value))
			cout << value;
	}
	cout << endl;
	infile.close();
	return 0;
}

首先定义了一个ifstream类的变量infile,打开文件a.txt,循环使用函数get读取文件里的字符并输出

getline()函数

getline函数的作用是读取一行信息到字符数组当中,在数组结尾加一个空字符\0,但是与get函数不同的一点就是getline函数会去除流中的分隔符,不存放到数组当中

#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
int main()
{
    
    
	char ch[256];
	ifstream examplefile("com.txt");
	if (!examplefile.is_open())
	{
    
    
		cout << "Error opening file";
		exit(1);
	}
	while (!examplefile.eof())
	{
    
    
		examplefile.getline(ch, 100);
		cout << ch << endl;
	}
	return 0;
}

首先定义了一个char类型的数组和一个ifstream类的变量,将文件打开后循环读取每一行文件中的内容并打印。
在C++中, char类型数组可以直接使用cout打印内容,cout会将char数组看做一个字符串,并将字符串中的内容打印出来

put()函数

put函数是用于写入字符串的函数

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    
    
	ofstream fout("a.txt");
	fout.put('a');
	fout.put('ed');
	fout.close();
}

猜你喜欢

转载自blog.csdn.net/leanneTN/article/details/113757715