cout
对象用于将输出显示到标准输出设备。它在 iostream 头文件中定义。
示例
#include <iostream>
using namespace std;
int main() {
int a = 24;
// print variable
cout << "Value of a is " << a;
return 0;
}
// Output: Value of a is 24
cout 语法
cout
对象的语法是
cout << var_name;
或者
cout << "Some String";
这里,
带有插入运算符的 cout
cout
中的 **"c"** 代表 **"character"** (字符),**"out"** 代表 **"output"** (输出)。因此,cout
的意思是 **"字符输出"**。
cout
对象与插入运算符 <<
一起使用,以显示字符流。例如,
int var1 = 25, var2 = 50;
cout << var1;
cout << "Some String";
cout << var2;
<<
运算符可以与变量、字符串和操纵符(如 endl
)组合多次使用。
cout << var1 << "Some String" << var2 << endl;
示例 1:带有插入运算符的 cout
#include <iostream>
using namespace std;
int main() {
int a,b;
string str = "Hello Programmers";
// single insertion operator
cout << "Enter 2 numbers - ";
cin >> a >> b;
cout << str;
cout << endl;
// multiple insertion operators
cout << "Value of a is " << a << endl << "Value of b is " << b;
return 0;
}
输出
Enter 2 numbers - 6 17 Hello Programmers Value of a is 6 Value of b is 17
带有成员函数的 cout
cout
对象还可以与其他成员函数一起使用,如 put()
、write()
等。一些常用的成员函数包括:
cout.put(char &ch):
显示由 ch 存储的字符。cout.write(char *str, int n):
显示从 str 读取的前 n 个字符。cout.setf(option):
设置给定的选项。常用的选项有left
(左对齐)、right
(右对齐)、scientific
(科学计数法)、fixed
(固定小数位数)等。cout.unsetf(option):
取消设置给定的选项。cout.precision(int n):
在显示浮点值时将小数精度设置为 n。与cout << setprecision(n)
相同。
示例 2:带有成员函数的 cout
#include <iostream>
using namespace std;
int main() {
string str = "Do not interrupt me";
char ch = 'm';
// use cout with write()
cout.write(str,6);
cout << endl;
// use cout with put()
cout.put(ch);
return 0;
}
输出
Do not m
cout 原型
cout
在 iostream 头文件中的原型如下:
extern ostream cout;
C++ 中的 cout
对象是 ostream
类的一个对象。它与标准 C 输出流 stdout
相关联。
cout
对象确保在 ios_base::Init
类型的对象首次构造期间或之前进行初始化。在 cout
对象构造完成后,它会与 cin 绑定,这意味着对 cin
的任何输入操作都会执行 cout.flush()
。
另请阅读