基本的输入输出(iostream)
C++标准库提供了一组丰富的输入/输出功能,C++的I/O发生在流中,流是字节序列。 如果字节流是从设备(键盘、磁盘驱动器、网络连接等)流向内存,叫做输入操作 。如果字节流是从内存流向设备(如显示屏、打印机、磁盘驱动器、网络连接等),叫做输出操作。
重要的头文件:
![](https://i-blog.csdnimg.cn/direct/5c73ffb30a2542b4978f453d6aded073.png)
setw主要用来控制输出的格式
标准输出流(cout)
预定义的对象cout是iostream类的一个实例。
cout对象连接到标准输出设备,通常是显示屏。cout与流插入运算符<<结合使用,如下所示:
cpp
#include <iostream>
using namespace std;
int main()
{
char c[] = "Hello world";
cout << c << endl;
return 0;
}
标准输入流(cin)
预定义的对象cin是iostream类的一个实例。
cin的对象附属到标准输入设备,通常是键盘。cin是与流提取运算符>>结合使用的,如下所示:
cpp
#include <iostream>
using namespace std;
int main()
{
char name[50];
cout << "您的姓名是:" << endl;
cin >> name;
cout << "您的姓名是:" << name << endl;
return 0;
}
文件操作(fstream)
![](https://i-blog.csdnimg.cn/direct/c88592125891427d8f4c2f7b198ca42e.png)
要在C++进行文件处理,必须在源代码文件中包含头文件**<iostream>** 和**<fstream>**
打开文件
ofstream和fstream都可以打开文件进行写操作, ifstream打开文件进行读操作
open()函数是ofstream、fstream、ifstream对象的一个成员函数
![](https://i-blog.csdnimg.cn/direct/048d8de711034f9ebac24feaef096fd4.png)
第一个参数指定要打开的文件名称和位置,第二个参数定义文件被打开的模式
第二个参数具体有以下五种模式:
![](https://i-blog.csdnimg.cn/direct/314fa9d0bf7c46b080d17267b81b617a.png)
以上模式可以结合使用。
例如,我们想要以写入模式打开文件,并希望截断文件,以防文件已经存在,可以使用下面的语法:
cpp
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc);
如果我们相打开一个文件用于读写,可以用以下语法:
cpp
ofstream outfile;
outfile.open("file.dat", ios::out | ios::in);
关闭文件
close()函数,是是ofstream、fstream、ifstream对象的一个成员函数。
cpp
void close();
示例
以读写模式打开一个文件,在向文件afile.dat写入用户输入的信息之后,程序从文件读取信息,并将其输出到屏幕上。
文件中数据的输入输出都是逐行进行的。
示例:
cpp
#include<fstream>
#include <iostream>
using namespace std;
int main()
{
char data[100];
//以写模式打开文件
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name" << endl;
cin.getline(data, 100);//从输入流中读取一行,直到遇到指定的终止字符或达到指定的字符数。
outfile << data << endl; //向文件中写入用户数据
cout << "Enter your age:";
cin >> data;
cin.ignore();//它通常用于清除输入缓冲区,以避免上一次输入影响下一次输入。(可以没有这一行)
outfile << data << endl;//再次向文件写入用户输入的数据
outfile.close();//关闭打开的文件
//以读模式打开文件
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;//从文件中输出数据到data
cout << data << endl;//data输出到屏幕上
infile >> data;//再次从文件读取数据
cout << data << endl;//再次显示数据
infile.close();//关闭打开的文件
return 0;
}