c++ io 流操作 以及字符串操作

字符流操作如下:

#include <fstream>
void main(){
	char* fname = "D://dest.txt";
	//打开输出流
	ofstream fout(fname);
	//创建失败
	if (fout.bad()){
		cout << "打开失败" << endl;
		return;
	}
	//向文本中写入内容
	fout << "jack" << endl;
	fout << "rose" << endl;
	fout.close();
	//读取
	ifstream fin(fname);
	if (fin.bad()){
		cout << "读取失败" << endl;
		return;
	}
	char ch;
	while (fin.get(ch)){
		cout << ch;
	}
	fin.close();

	system("pause");
}

字节流操作:

void main(){
	char* src = "D://lgj.jpg";
	char* dest = "D://copylgj.jpg";
	//输入流,最后一个参数是
	ifstream fin(src,ios::binary);
	ofstream fout(dest,ios::binary);
	if (fin.bad() || fout.bad()){
	
		return;
	}
	while (!fin.eof()){
		char buffer[1024] = {0};
		//读取
		fin.read(buffer,1024);
		//写入
		fout.write(buffer,1024);
	}
	fin.close();
	fout.close();
	system("pause");
}

把对象序列化到硬盘上操作:

void main()
{
	Person p1("柳岩", 22);
	Person p2("rose", 18);
	//输出流
	ofstream fout("c://c_obj.data", ios::binary);
	fout.write((char*)(&p1), sizeof(Person)); //指针能够读取到正确的数据,读取内存区的长度
	fout.write((char*)(&p2), sizeof(Person));
	fout.close();

	//输入流
	ifstream fin("c://c_obj.data", ios::binary);
	Person tmp;
	fin.read((char*)(&tmp), sizeof(Person));
	tmp.print();

	fin.read((char*)(&tmp), sizeof(Person));
	tmp.print();

	system("pause");

}

字符串操作

void main()
{
	string s1 = "lgj ";
	string s2(" lt ");
	string s3 = s1 + s2;

	cout << s3 << endl;
	
	//转c字符串
	const char* c_str = s3.c_str();
	cout << c_str << endl;

	//s1.at(2);


	system("pause");
}

容器

//容器
#include <vector>

void main()
{
	//动态数组
	//不需要使用动态内存分配,就可以使用动态数组
	vector<int> v;
	v.push_back(12);
	v.push_back(10);
	v.push_back(5);

	for (int i = 0; i < v.size(); i++)
	{
		cout << v[i] << endl;
	}

	system("pause");
}

猜你喜欢

转载自blog.csdn.net/weixin_39413778/article/details/82972880