📜  C++基本输入/输出

📅  最后修改于: 2020-12-17 05:09:16             🧑  作者: Mango


C++标准库提供了广泛的输入/输出功能集,我们将在后续章节中看到。本章将讨论C++编程所需的非常基本和最常见的I / O操作。

C++ I / O发生在流中,流是字节序列。如果字节从键盘,磁盘驱动器或网络连接等设备流向主内存,则这称为输入操作,并且如果字节从主存储器流向显示屏,打印机,磁盘驱动器等设备或网络连接等,这称为输出操作

I / O库头文件

以下是对C++程序很重要的头文件-

Sr.No Header File & Function and Description
1

This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream, the standard output stream, the un-buffered standard error stream and the buffered standard error stream, respectively.

2

This file declares services useful for performing formatted I/O with so-called parameterized stream manipulators, such as setw and setprecision.

3

This file declares services for user-controlled file processing. We will discuss about it in detail in File and Stream related chapter.

标准输出流(cout)

预定义的对象coutostream类的实例。 cout对象被称为“连接到”标准输出设备,通常是显示屏。 cout与流插入运算符结合使用,该运算符写为<<,比下面的示例中的符号少两个。

#include 
 
using namespace std;
 
int main() {
   char str[] = "Hello C++";
 
   cout << "Value of str is : " << str << endl;
}

编译并执行上述代码后,将产生以下结果-

Value of str is : Hello C++

C++编译器还确定要输出的变量的数据类型,并选择适当的流插入运算符以显示该值。 <<运算符被重载以输出内置类型整数,浮点数,双精度数,字符串和指针值的数据项。

如上所示,插入运算符<<可以在单个语句中多次使用,并且endl用于在该行的末尾添加换行。

标准输入流(cin)

预定义对象cinistream类的实例。据说cin对象已连接到标准输入设备,通常是键盘。 cin与流提取运算符结合使用,该运算符写为>>,比下面的示例中的符号大两个。

#include 
 
using namespace std;
 
int main() {
   char name[50];
 
   cout << "Please enter your name: ";
   cin >> name;
   cout << "Your name is: " << name << endl;
 
}

编译并执行上述代码后,它将提示您输入名称。输入一个值,然后按Enter键以查看以下结果-

Please enter your name: cplusplus
Your name is: cplusplus

C++编译器还确定输入值的数据类型,并选择适当的流提取运算符以提取值并将其存储在给定变量中。

在单个语句中,可以多次使用流提取运算符>>。要请求多个基准,可以使用以下命令:

cin >> name >> age;

这将等效于以下两个语句-

cin >> name;
cin >> age;

标准错误流(cerr)

预定义对象cerrostream类的实例。据说cerr对象已附加到标准错误设备上,该设备也是一个显示屏,但是对象cerr是未缓冲的,每次插入cerr的流都会导致其输出立即出现。

cerr也与流插入运算符结合使用,如以下示例所示。

#include 
 
using namespace std;
 
int main() {
   char str[] = "Unable to read....";
 
   cerr << "Error message : " << str << endl;
}

编译并执行上述代码后,将产生以下结果-

Error message : Unable to read....

标准日志流(Clog)

预定义的对象阻塞ostream类的实例。阻塞对象被认为是附加到标准错误设备上的,该设备也是一个显示屏,但是对象阻塞已被缓冲。这意味着每次插入阻塞都会导致其输出保留在缓冲区中,直到缓冲区被填充或缓冲区被刷新为止。

阻塞还可以与流插入运算符结合使用,如以下示例所示。

#include 
 
using namespace std;
 
int main() {
   char str[] = "Unable to read....";
 
   clog << "Error message : " << str << endl;
}

编译并执行上述代码后,将产生以下结果-

Error message : Unable to read....

通过这些小示例,您将看不到cout,cerr和clog的任何区别,但是在编写和执行大型程序时,区别变得明显。因此,最好的做法是使用cerr流显示错误消息,并在显示其他日志消息时使用clog。