输入输出流知识点总结

基本流类

ios:基本流类的基类
stream:由ios派生,支持输入(提取“>>”)操作
ostream:由ios派生,支持
输出(插入“<<”)操作
ostream:由istream与ostream共同派生,支持输入和输出双向操作
用于磁盘操作的文件流类
ifstream:由istream派生,支持从磁盘文件中
输入(读)数据

ofstream:由ostream派生,支持往磁盘文件中输出(写)数据
fstream:由iostream派生,支持对磁盘文件进行输入和输出数据的双向操作

1.标准输入输出流对象

C++预定义了4个标准流对象:cin、cout、cerr、clog,均包含于头文件iostream中
cin是istream类的对象,用于处理标准输入(即从键盘输入数据到内存中)
cout是ostream类的对象,用于处理标准输出(即将内存中的数据输出到屏幕上)
cerr和clog都是ostream类的对象,均用于处理错误信息标准输出

2.提取操作符

提取“>>”插入“<<”
重载函数operator>>()、operator<<()以引用方式返回调用该函数时所使用的对象,因此能够连续提取

使用<<和>>操作用户自定义类型:重载插入与提取运算符

class complex {
	double r;
	double i;
public:
	complex(double r0 = 0, double i0 = 0) {
		r = r0; i = i0;
	}
	complex operator +(complex c2);
	complex operator *(complex c2);
	friend istream& operator>>(istream& in, complex& com);
	friend ostream& operator<<(ostream& out, complex com);
};
istream& operator>>(istream& in, complex& com)
{
	in >> com.r >> com.i;
	return in;//不可缺少,因为函数返回类型为“istream&”
}
ostream& operator << (ostream& out, complex com) {
	out << "(" << com.r << "," << com.i << ")" << endl;
	return out; //不可缺少,因为函数返回类型为“ostream&”
}

3.输入输出流函数

①put()——插入

输出一个字符(字符型参数),格式为:ostream& put( char ch )

char ch='a';
cout.put(ch);
//在屏幕上输出变量ch中存储的字符'a'
cout.put(‘b’).put(‘c’)<<endl;
//因为返回引用,可以连续调用

②get()——提取

提取一个字符(存放在字符型参数),格式为:istream& get( char& rch );

char ch, ch1;
cin.get(ch);
//从键盘上读入字符,并存放在字符变量ch中
cin.get(ch).get(ch1)<<endl;
//连续从键盘上读入两个字符,放到ch和ch1中

get()函数和运算符“>>”的区别在于:get()函数能够读取空格、回车符和制表符等空白字符,而“>>”只能读取非空白字符

③getline()

从输入设备读入一行,格式为:istream& getline(char* pch, int n,char delim = '\n')
1.从输入设备读取n-1个字符,并在其后加上字符串结束符’\0’,存入第1个参数所指向的内存空间中
2.若在读取够n-1个字符前遇到由第3个参数指定的终止符,则提前结束读取,终止符的默认值是'\n'
3.若读取成功,函数返回值为真(非0)值,若读取失败(遇到文件结束符EOF),函数返回值为假(0)值
getline()能够读取空格、回车符和制表符等空白字符

int main() {
	int len, maxlen = 0;
	char s[80], t[80];
	while (cin.getline(s, 80)) {
		len = (int)strlen(s);
		if (len > maxlen) {
			maxlen = len;
			strcpy_s(t, s);
		}
	}
	cout << "长度最大的字符串是:" << t << endl;
	cout << "其长度为:" << maxlen << endl;
	return 0;
}

另一种写法:istream& getline(istream &is, string&str, char delim='\n'
从输入设备读取字符串,放在str中,直到遇到结尾符delim;或者读到文件末尾
若读取成功,函数返回值为真(非0)值,若读取失败(遇到文件结束符EOF),函数返回值为假(0)值

int main() {
	string name;
	string city;
	cout << "Please enter your name: ";
	getline(cin, name);
	cout << "Enter the city: ";
	getline(cin, city);
	cout << "Hello," << name << endl;
	cout << "You live " << city << endl;
	return 0;
}

4.输入输出格式

一、控制I/O格式的第一种方式是使用ios类的公有函数

1.ios类中定义了一批公有的格式控制标志来控制格式
状态标志含义
left左对齐输出
right右对齐输出
hex十六进制
dec
oct八进制
showpoint输出时显示小数点
scientific科学示数法显示浮点数
fixed定点形式显示浮点数

多个标志位可以组合,例如,ios::fixed | ios::left 表示以定点形式左对齐输出浮点数
每个格式标志用一个long型常数表示,且只有一个bit是1,其余bit都是0
eg:

状态标志含义
long setf(long lFlags)设置lFlags指定的标志位
long setf(long lFlgas,long lMask);将lMask指定的位清0,然后设置lFlags制定位
long flags(long lFlags);用参数Flags更新标志字
long flags() const;返回标志字
cout.setf(ios :: left)
cout.setf(ios :: right, ios ::left);
2.通过ios类的公有函数控制I/O格式

比如,char fill(char cFill); 空白位置以字符参数cFill填充,int width(int nw);设置下一个输出项的显示宽度为nw,int precision(int np); 用参数np设置数据显示精度

int main() {
	const char* s = "Hello";
	cout.fill('*'); // 置填充符
	cout.width(10); // 置输出宽度
	cout.setf(ios::left); // 左对齐
	cout << s << endl;
	cout.width(15); // 置输出宽度
	cout.setf(ios::right, ios ::left);// 清除左对齐标志位,置右对齐
	cout << s << endl;
	return 0;
}

输出结果:
Hello*****
**********Hello

int main() {
	float a = 123.4567;
	cout.flags(ios::right | ios::fixed);
	// 置右对齐、定点输出,默认保留6位小数
	cout << a << endl;
	cout.flags(ios::left |ios::scientific);
	// 置左对齐、科学计数法
	cout.precision(2); //保留2位小数
	cout << a << endl;
	cout.flags(ios::left);
	cout.precision(6);
	cout << a << endl;
	return 0;
}

输出结果:
123.456703
1.23e+02
123.457

int main() {
	int a, b, c;
	cin.setf(ios::dec, ios::basefield);
	cin >> a; //改为十进制输入,之前的进制清除
	cin.setf(ios::hex, ios::basefield);
	cin >> b; //十六进制输入
	cin.setf(ios::oct, ios::basefield);
	cin >> c; //八进制输入
	cout.setf(ios::dec, ios::basefield);
	cout << a << " " << b << " " << c << endl; //十进制输出
	cout.setf(ios::hex, ios::basefield);
	cout << a << " " << b << " " << c << endl; //十六进制输出
	cout.setf(ios::oct, ios::basefield);
	cout << a << " " << b << " " << c << endl; //八进制输出
	cout << endl;
	cout << dec << a << hex << b << hex << c << endl;
	return 0;
}

basefield:之前的进制清除;两种方式均可

二、控制I/O格式的第二种方式是使用格式控制符

控制符作为重载插入运算符<<或提取运算符>>的右操作数控制I/O格式

iomanip的控制符功能
resetiosflags(ios::lFlags)清除lFlags指定的标志位
setiosflags(ios::lFlags)设置lFlags指定的标志位
setbase(int base)设置基数,base=8, 10, 16
setfill(char c)设置填充符c
setprecision(int n)设置浮点数输出精度
setw(int n)设置输出宽度
#include <iomanip>
int main() {
	const char* s = "Hello";
	cout.fill('*');
	cout.width(10);
	cout.flags(ios::left);
	cout << s << endl;
	cout.fill('*');
	cout.width(15);
	cout.flags(ios::right);
	cout << s << endl;

	cout << setw(10) << setfill('*') << left << s << endl;
	cout << setw(15) << setfill('*') << right << s << endl;
	return 0;
}

当格式为ios::scientific或ios::fixed时,浮点数精度np指小数点后的位数,否则指有效数字

void main() {
	cout.width(6); //只管随后一个数的域宽,默认右对齐
	cout << 4785 << 27.4272 << endl; 
	cout << setw(6) << 4785 << setw(8) << 27.4272 << endl;
	cout.width(6);
	cout.precision(3);
	/*当格式为ios::scientific或ios::fixed时,浮点数精度np指
	小数点后的位数,否则指有效数字;此例中没有fixed或
	者scientific,所以指的是有效数字为3*/
	cout << 4.785 << setw(8) << 27.4272 << endl;
	cout << setw(6) << setprecision(2) << 4785 << setw(8) << setprecision(2);
	cout << 27.4272 << endl;
	//setprecision(2)设置浮点数的有效数字
	cout.setf(ios::fixed, ios::floatfield);
	//今后以定点格式显示浮点数(无指数部分)
	cout.width(6);
	cout.precision(3);
	//当格式为ios::fixed时,设置小数点后的位数
	cout << 4785 << setw(8) << 27.4272 << endl;
}

5.cin/cout缓冲区

步骤一:键盘输入1 2两个整数,中间空格隔开
步骤二:输入回车,1 2被送入缓冲
步骤三:cin从缓冲区读取数据,赋值给a和b
(1)读取整数1(以空格/回车/Tab作为分隔符),赋值给a
(2)读取整数2,赋值给b

int main() {
	int a;
	int i = 1;
	while (cin >> a) {
		cout << a << endl;
		i++;
		if (i == 5)
			break;
	}
	char ch;
	cin >> ch;
	cout << "ch: " << ch;
	return 0;
}

运行结果:
1
2
3
4
ch: 5
(1)缓冲区中1 2 3 4 5;(2)while循环只读取了前4个数字;(3)cin>>ch并没有等待用户输入,直接从缓冲区读取了第5个数字
解决方案:下次cin之前清空缓冲区
cin.clear(); cin.ignore(numeric_limits<std::streamsize>::max(),'\n');

int main() {
	int a, i = 1;
	while (cin >> a) {
		cout << a << endl;
		i++;
		if (i == 5) break;
	}
	cin.clear();
	cin.ignore(numeric_limits<std::streamsize>::max(),'\n');
	char ch;
	cin >> ch;
	cout << "ch: " << ch;
	return 0;
}

磁盘文件输入输出

1.C++通过文件流类实现对磁盘文件的输入输出
2.C++中没有预定义的文件流类的对象,用户需要为每个文件自己定义文件流类对象
3.引入头文件
读写磁盘文件的一般处理过程:打开文件=>读写操作=>关闭文件

1.ofstream、ifstream、fstream

1.打开文件
①通过构造函数自动打开文件:ifstream infile(“myfile.txt”);
②通过open函数显示地打开文件:
ofstream outfile; outfile.open(“myfile.txt”)
①文件输出流 ofstream
ofstream构造函数:ofstream(const char* szName, int nMode=ios::out)
szName – 文件名,nMode – 文件打开方式

文件打开方式作用
ios::out以输出方式打开文件,对文件进行写操作(首次打开文件,创建新文件;打开已有文件,保留原有内容,以追加方式写文件)
ios::app以追加方式打开文件,所有输出附加在文件末尾
ios::ate打开文件时,文件指针定位在文件尾
ios::binary以二进制方式打开文件,缺省的方式是文本方式
ios::trunc如果文件已存在,则先删除文件内容

默认是ios::out,多种mode可以用位或运算符(即“|”)连接,如ios::out | ios:binary
②文件输入流 ifstream
ifstream(const char* szName, int nMode=ios::in);

文件打开方式作用
ios::in以输入方式打开文件,对文件进行读操作,该文件必须存在
ios::binary以二进制方式打开文件,缺省的方式是文本方式
ios::ate打开文件时,文件指针定位在文件尾

默认是ios::in,多种mode可以用位或运算符(即“|”)连接,如ios::in | ios::binary

int main() {
	int x1 = 0, x2 = 0;
	ofstream outfile("myfile.txt", ios::out);
	outfile << 16;//写入16
	outfile.close();
	//打开文件,默认从文件头开始读
	ifstream infile("myfile.txt", ios::in);
	infile >> x1;
	infile.close();
	return 0;
}

③文件输入输出流 fstream(可以读又可以写)
fstream(const char* szName, int nMode = ios::in |ios::out);

文件流类的构造函数
一些规则
os::app 以追加的方式打开文件
ios::ate 打开文件时将文件指针放在文件末尾

ios::app一般只和ios::out配合,用于以追加的方式打开输入流:fstream fs(“aaa.txt”, ios::out | ios::app)
ios::ate一般和ios::in相配合,打开文件时将文件指针定位到文件尾:fstream fs(“aaa.txt”, ios::in | ios::ate);
如果ios::ate和ios::out相结合,将清空原文件:fstream fs(“aaa.txt”, ios::out | ios::ate);
文件不存在时,是否创建新的文件
fstream 在文件不存在时创建新文件的条件:1)单独使用 ios::out;2)同时使用 ios::out | ios::trunc

2.文件流类的open成员函数

ofstream::openvoid open( const char* szName, int nMode = ios::in);
ifstream::openvoid open( const char* szName, int nMode = ios::in
fstream::openvoid open( const char* szName, int nMode = ios::out);
#include<fstream>
#include<iostream>
using namespace std;
int main() {
	ofstream outfile;
	outfile.open("myfile.txt");
	if (!outfile.is_open()) { //判断是否打开成功
		cout << "打开文件失败!" << endl;
		return 0;
	}
	outfile << "Write to file";
	outfile.close();
	return 0;
}

3.使用<<和>>读写文件

①使用插入运算符<<写文件

ios::in:读文件 ios::out:写文件

文件流类可以使用插入运算符写文件

#include<fstream>
#include<iostream>
using namespace std;
int main() {
	int x = 1;
	double y = 2.3;
	char z = '3';
	ofstream outfile("myfile.txt", ios::out | ios::app);
	outfile << x;
	outfile << endl;
	outfile << y;
	outfile << endl;
	outfile << z;
	outfile.close();
	return 0;
}

②使用提取运算符>>读文件

#include<fstream>
#include<iostream>
using namespace std;
int main() {
	int x;
	double y;
	char z;
	fstream infile("myfile.txt", ios::in);
	infile >> x;
	infile >> y;
	infile >> z;
	infile.close();
	cout << x << y << z;
	return 0;
}

③应用举例

#include <iostream>
#include <fstream>
using namespace std;
int main() {
	fstream outfile; //使用fstream类对象
	//以写方式打开文本文件digit.txt
	outfile.open("digit.txt", ios::out);
	if (!outfile.is_open()) 
	{ //判断是否打开成功
		cout << "打开digit.txt文件失败!" << endl;
		return 0;
	}
	char digit = '0';
	//循环将10个数字字符输出到文件digit.txt中
	while (digit <= '9') {
		outfile << digit << ' ';//将digit写入文件
		digit++;
	}
	outfile.close(); //关闭文件
	//以读方式打开文本文件
	fstream infile("digit.txt", ios::in);
	if (!infile.is_open()) 
	{ //判断是否打开成功
		cout << "打开digit.txt文件失败!" << endl;
		return 0;
	}
	// 循环从文件中读取数字字符到变量digit中
	while (infile >> digit) 
	{
		cout << digit << ' ';
	}
	cout << endl;
	infile.close();
	return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main() {
	//1) 往文件写数据
	ofstream outfile1("myfile1.txt");
	//以“写”方式打开
	outfile1 << "Hello!...CHINA! Nankai_University"<<endl;
	outfile1.close();
	//2) 往文件尾部追加数据
	outfile1.open("myfile1.txt", ios::app);
	//以“追加”方式打开
	int x = 1212, y = 6868;
	outfile1 << x << " " << y << endl;
	//注意,数据间要人为添加分割符空格
	outfile1.close();

	char str1[80], str2[80];
	int x2, y2;
	ifstream infile1("myfile1.txt");
	//以读方式打开
	infile1 >> str1 >> str2;
	//使用“>>”读(遇空格、换行均结束)
	infile1 >> x2 >> y2;
	infile1.close();
	cout << "str1=" << str1 << endl;
	cout << "str2=" << str2 << endl;
	cout << "x2=" << x2 << endl;
	cout << "y2=" << y2 << endl;
}

运行结果:
str1=Hello!..CHINA!
str2=Nankai_University
x2=1212
y2=6868
注意:使用“>>”读(遇空格、换行均结束)

4.使用put和get函数读写文件

1.文件流类可以使用put和get、getline函数读写文件

put/get只能一个字符一个字符来,但是可以存空格等<<、>>无法读或写的内容

#include <iostream>
#include <fstream>
using namespace std;
int main() {
	char str[80];
	cout << "Input string:" << endl;
	cin.getline(str, 80);
	ofstream fout("putgetfile.txt");
	int i = 0;
	while (str[i])
	{
		fout.put(str[i++]);
	}
	fout.close();
	cout << "--------------------" << endl;
	//而后使用get从文件中读出该串显示在屏幕上
	char ch;
	ifstream fin("putgetfile.txt");
	fin.get(ch);
	while (!fin.eof()) 
	{
		//从头读到文件结束(当前符号非文件结束符时继续)
		//注: 成员函数eof()在读到文件结束时方返回true
		cout << ch;
		fin.get(ch);
	}
	cout << endl;
	fin.close();
}

2.文件流类可以使用getline按行读文件

#include <iostream>
#include <fstream>
using namespace std;
int main() {
	char line[81];
	ifstream infile("putgetfile.cpp");
	infile.getline(line, 80);
	//读出一行(至多80个字符)放入line中
	while (!infile.eof()) {
		//尚未读到文件结束则继续循环(处理)
		cout << line << endl; //显示在屏幕上
		infile.getline(line, 80);//再读一行
	}
	infile.close();
}

5.文本文件和二进制文件

文本文件:数据按ASCII码存在文件中
12.345以文本方式写入文件时,会自动将每个数字(包括小数点)都转换为ASCII码来存,所以一共要存6个字节,分别是’1’,’2’,’.’,’3’,’4’,’5’的ASCII码

int main() {
	double d = 12.345;
	ofstream outfile("asc.txt");
	outfile << d;
	outfile.close();
}

二进制文件:数据按内存的格式存在文件中
12.345在内存中占8个字节,以补码形式存储(0X713D0AD7A3B02840),用write函数写入文件时,直接将内存中的8个字节拷贝到文件中

int main() {
	double d = 12.345;
	ofstream outfile("asc.txt", ios::binary);//ofstream按二进制方式打开
	outfile.write((char*)&d, sizeof(d));//以二进制方式写入文件
	outfile.close();
}

6.read()和write()读写二进制文件

istream& read(char* pch, int nCount)
功能:从文件中读入nCount个字符放入pch缓冲区中(若读至文件结束尚不足nCount个字符时,也将立即结束本次读取过程)
ostream& write(const char* pch, int nCount)
功能:将pch缓冲区中的前nCount个字符写出到某个文件中

先使用write往自定义二进制磁盘文件中写出如下3个“值”:字符串str的长度值Len字符串str本身、以及一个结构体的数据,而后再使用read读出这些“值”并将它们显示在屏幕上(write可以读结构体)

#include <iostream>
#include <fstream>
using namespace std;
struct stu {
	char name[20];
	int age;
	double score;
};
void main() {
	char str[20] = "Hello world!";
	stu ss = { "wu jun", 22, 91.5 }, aa;
	ofstream fout("wrt_read_file.bin", ios::binary);
	//打开用于“写”的二进制磁盘文件
	int Len = strlen(str);
	fout.write((char*)(&Len), sizeof(int));
	fout.write(str, Len);
	//数据间无需分割符
	fout.write((char*)(&ss), sizeof(ss));
	fout.close();

	char str2[80];
	ifstream fin("wrt_read_file.bin", ios::binary);
	fin.read((char*)(&Len), sizeof(int));
	fin.read(str2, Len);
	str2[Len] = '\0';
	fin.read((char*)(&aa), sizeof(aa));
	cout << "Len=" << Len << endl;
	cout << "str2 = " << str2 << endl;
	cout << "ss=>" << aa.name << "," << aa.age << "," << aa.score << endl;
	fin.close();
}

设置文件的类型
由程序员决定将数据存储为文本文件或者二进制文件
1.缺省打开方式时,默认为文本文件形式。若欲使用二进制文件形式 ,要将打开方式设为“ios::binary”
2.通常将纯文本信息(如字符串)以文本文件形式存储,而将数值信息以二进制文件形式存储
3.通常使用read()与write()对二进制文件进行读写

7.对数据文件进行随机访问

文件的随机读写,需要移动文件指针
seekg()和seekp(): 定位输入文件流对象和输出文件流对象的文件指针

istream& seekg(long offset, seek_dir origin=ios::beg);
ostream& seekp(long offset, seek_dir origin=ios::beg);

功能:将文件指针从参照位置origin移动offset个字节
offset是长整型,取值为正表示向后移动文件指针,取值为负则表示向前移动文件指针
origin为参照位置,seek_dir是系统定义的枚举类型,有3个枚举常量

ios::beg:文件首
ios::cur:文件指针当前位置
ios::end:文件尾
// 将输入文件流对象的文件指针从当前位置向前移5个字节
infile.seekg(-5, ios::cur);
// 将输出文件流对象的文件指针从文件首向后移5个字节
outfile.seekp(5, ios::beg);

1.在进行文件的随机读/写时,可使用**tellg()和tellp()**函数获取文件指针的当前位置
2.对于fstream对象,则既可使用seekg()和tellg()函数,也可使用seekp()和tellp()函数,结果完全一样

#include <iostream>
#include <fstream>
using namespace std;
void main() {
	int a[8] = { 0,1,-1,1234567890 };
	for (int i = 4; i < 8; i++)
		a[i] = 876543210 + i - 4;
	//均由9位数字组成,在text文件中所占字节数也为9
	ofstream ft("ft.txt");
	ofstream fb("fb.bin", ios::binary);
	for (int i = 0; i < 8; i++) {
		//向文本文件和二进制文件内写入内容
		ft << a[i] << " "; //数据间需要添加分割符
		fb.write((char*)(&a[i]), sizeof(a[i]));
		//数据间不需分割符

		//读取文本文件和二进制文件的内容
		cout << "ft.tellp()=" << ft.tellp() << ",";
		//当前ft文件位置
		cout << "fb.tellp()=" << fb.tellp() << endl;
		//当前fb文件位置
	}
	ft.seekp(-5, ios::cur);
	cout << "ft.tellp()=" << ft.tellp() << ",";
	ft.close();
	fb.close();
}

运行结果:
ft.tellp()=2(文件指针在0之后,数字字符0的长度为1),fb.tellp()=4(文件指针在0之后,数字为int类型的长度为4字节)
ft.tellp()=4(数字字符长度为1,走一步),fb.tellp()=8(往后走一个int型的整数,长度+4)
ft.tellp()=7(数字字符长度为2,走两步),fb.tellp()=12
ft.tellp()=18(数字字符长度为9,走九步),fb.tellp()=16
ft.tellp()=28,fb.tellp()=20
ft.tellp()=38,fb.tellp()=24
ft.tellp()=48,fb.tellp()=28
ft.tellp()=58,fb.tellp()=32
ft.tellp()=53,

将3名学生的学号、姓名和成绩写入二进制文件studentinfo.dat中,再将第2名学生的成绩改为627,最后从文件中读取第m(m的值由用户从键盘输入)名学生的信息并将其输出到屏幕上

#include<iostream>
#include<fstream>
using namespace std;
struct Student
{
	char num[10];
	char name[20];
	int score;
};
int main() {
	Student stu[3] = {{"1210101","张三", 618},{"1210102","李四", 625},{"1210103","王五", 612}};
	int i, m;
	fstream outfile("studentinfo.dat", ios::binary | ios::out);
	for (i = 0; i < 3; i++)
		outfile.write((char*)&stu[i],sizeof(Student)); //将学生信息写入文件
	outfile.close();

	outfile.open("studentinfo.dat", ios::binary | ios::in | ios::out);
	stu[1].score = 627;
	// 将文件指针定位到第2名学生数据开始的位置
	outfile.seekp(1 * sizeof(Student), ios::beg);
	// 用新数据覆盖原来文件中保存的第2名学生的数据
	outfile.write((char*)&stu[1], sizeof(Student));
	outfile.close();

	cout << "请输入待查询的学生序号(1~3):";
	cin >> m;
	if (m < 1 || m>3) {
		cout << "学生不存在!" << endl;
		return 0;
	}
	//以读方式打开二进制文件
	fstream infile("studentinfo.dat", ios::binary | ios::in);
	//将文件指针定位到第m名学生数据开始的位置
	infile.seekg((m - 1) * sizeof(Student), ios::beg);
	//将指定学生的数据读入到内存中
	infile.read((char*)&stu[m - 1], sizeof(Student));
	cout << "第" << m << "名学生信息:" << endl;
	cout << stu[m - 1].num << "," << stu[m - 1].name << "," << stu[m - 1].score << endl;
	infile.close();
	return 0;
}

字符串流

字符串流类对象并不对应于一个具体的物理设备,而是将内存中的字符数组看成是一个逻辑设备,并通过“借用”对文件进行操作的各种运算符和函数,最终完成上述所谓的信息转换工作
使用字符串流类时,必须包含头文件strstream

1.ostrstream类

ostrstream类将不同类型的信息转换为字符串,并存放在(输出到)用户设定的字符数组中
该类最常用的构造函数的一般格式为:ostrstream(char* str, int n, int mode = ios::out)

#include <iostream>
#include <strstream>
using namespace std;
int main() {
	int a = 123;
	char* pbuffer = new char[10];
	ostrstream ostr(pbuffer, 10, ios::out);
	ostr << a; //将123变为字符串,放在pbuffer中
	ostr << 4.5<< ends; //将4.5变为字符串,接在后面
	//ends是增加字符串结尾符
	cout << pbuffer; //输出1234.5
	delete[] pbuffer;
	return 0;
}
#include<fstream>
#include<iostream>
#include<strstream>
using namespace std;
int main() {
	ostrstream os; //未指定字符数组,系统来分配
	string str = "abcef";
	int i = 1000;
	os << str << i; //将str和i连成一个字符串,存放在系统分配的空间中
	cout << os.str() << endl; //输出"abcef1000"
	cout << os.pcount(); //ostrstream成员函数,统计当前已经输出了多少个字符
	return 0;
}

2.istrstream类

istrstream类可将用户字符数组中的字符串取出(读入),而后反向转换为各种变量的内部形式
一参构造函数:istrstream(char* str );,由参数str 指定一个以‘\0’为结束符的字符串(字符数组)
二参构造函数:istrstream(char* str, int n );,由参数str 指定字符数组,由第二参数n 指出仅使用str的前n个字符
二参构造函数时,并不要求str 中必须具有‘\0’结束符号若n=0,则假定str 为一个以‘\0’为结束符号的字符串(字符数组)

#include<fstream>
#include<iostream>
#include<strstream>
using namespace std;
int main() {
	const char* str = "1234 100.35 ";
	istrstream inp(str);
	int nNumber;
	float balance;
	inp >> nNumber; //从字符串中拆出整数1234
	inp >> balance; //从字符串中拆出float 100.35
	cout << nNumber << ' ' << balance;
}

3.stringstream字符串流类

由iostream继承
支持string类型的字符串流类
1.ostringstream向string写数据
2.istringstream从string读数据
3.stringstream即可从string读数据,也可以像string写数据
主要成员:
stringstream::str():返回字符串流保存的string

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
	stringstream ostr("ccc"); //初始字符串为”ccc”
	ostr.put('d'); //向字符串添加’d’,注意从字符串开头增加,即覆盖掉第1个’c’
	ostr.put('e'); //向字符串添加’e’,覆盖掉第2个’c’
	string gstr = ostr.str();
	cout << gstr << endl; //输出”dec”
	char a;
	ostr >> a;
	cout << a;
}

*4.stringstream类的对象常用来进行string与各种内置类型数据之间的转换

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
	stringstream sstr;
	//--------int转string-----------
	int a = 100;
	string str;
	sstr << a; //将100写入sstr
	sstr >> str; //将100转为string
	cout << str << endl;

	//--------string转char[]--------
	stringstream sstr1;
	char a1[100];
	sstr1 << a;
	//sstr1在转换时自行加'\0'
	sstr1 >> a1;
	cout << a1;
}
  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值