【1.2】c语言--流

一、标准输入输出流

cin >> x;
  • 读入整型数时以第一个非数字为终结
  • 读入字符串时以第一个空格、tab 或换行符为终结

其他例子

cin.getline (str, len, ch);  // 读入一个字符串
							// ch被从流中提出,但不存入str
ch = cin.get();   // 读入一个单独的字符
cin.ignore (len, ch);  // 忽略一串字符, ch同上

cin >> x;

判断读入结束:
    int x; while(cin>>x){
		..... 
	}
	return 0; 
键盘读入时用ctrl-z结束,文件读入时读到文件末尾	

cout << y;

cout 输出到标准设备

cerr 输出错误信息

clog 输出错误日志

cout << y;

输出一个字符:

cout.put(‘A’).put(‘a’);

二、流操纵算子

cout << y;

整型数:

int n = 10;
cout << n << endl;
cout << hex << n << endl
	<< dec << n << endl 
	<< oct << n << endl;

浮点数

#include <iostream> 
#include <iomanip> 
using namespace std; 
int main()
{

	double x = 1234567.89,y = 12.34567; 
	int n = 1234567;
	int m = 12;
	cout << setprecision(6) << x << endl
		<< y << endl << n << endl << m;
}

浮点数

#include <iostream> 
#include <iomanip> 
using namespace std; 
int main()
{

	double x = 1234567.89,y = 12.34567; 
	int n = 1234567;
	int m = 12;
	cout << setiosflags(ios::fixed)  <<
		setprecision(6) << x << endl
		<< y << endl << n << endl << m;
}

设置域宽

输入:1234567890

cin.width(5);
cin >> string;
cout << string << endl; cin >> string;
cout << string << endl;

三、文件输入输出流

基本操作与cin和cout相同

ifstream fin; ofstream fout;
fin.open (“input.txt”); fout.open (“output.txt”,ios::out); 
fin>>...
fout << ...

打开文件选项

ios::out 输出到文件, 删除原有内容
ios::app 输出到文件, 保留原有内容,总是在尾部添加
ios::ate 输出到文件, 保留原有内容,可以在文件任意位置添加

文件指针操作: 输入文件指针操作 为 tellg, seekg

ofstream fout(“a1.out”,ios::ate); 
long location = fout.tellp();
	//取得写指针的位置 location = 10L;
fout.seekp(location);
输入文件指针操作 为 tellg, seekg
   // 将写指针移动到第10个字节处 
fout.seekp(location,ios::beg); //从头数location 
fout.seekp(location,ios::cur); //从当前位置数location 
fout.seekp(location,ios::end); //从尾部数location

参考资料

北京大学 《数据结构与算法》 张铭、赵海燕、宋国杰、黄骏、邹磊、陈斌、王腾蛟

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn