在本教程中,我们将借助示例了解 C++ cout 对象。
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 << var_name;
或者
cout << "Some String";
这里,
<<是插入运算符var_name通常是变量,但也可以是数组元素或容器元素,如向量、列表、Map等。
cout 与插入运算符
"c"在cout指"character"和"out"方法"output".因此cout方法"character output".
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 原型
iostream 头文件中定义的cout 原型为:
extern ostream cout;
C++ 中的 cout 对象是类 ostream 的对象。它与标准 C 输出流 stdout 相关联。
cout 对象确保在第一次构造ios_base::Init 类型的对象期间或之前被初始化。构造 cout 对象后,它与 cin 绑定,这意味着 cin 上的任何输入操作都会执行 cout.flush() 。
相关用法
- C++ count()用法及代码示例
- C++ count_if()用法及代码示例
- C++ copy_n()用法及代码示例
- C++ complex cosh()用法及代码示例
- C++ copy()用法及代码示例
- C++ copy_backward()用法及代码示例
- C++ cosh()用法及代码示例
- C++ cos()用法及代码示例
- C++ copysign()用法及代码示例
- C++ copy_if()用法及代码示例
- C++ complex cos()用法及代码示例
- C++ conj()用法及代码示例
- C++ clock()用法及代码示例
- C++ clog用法及代码示例
- C++ cbrt()用法及代码示例
- C++ c32rtomb()用法及代码示例
- C++ c16rtomb()用法及代码示例
- C++ cin用法及代码示例
- C++ ctime()用法及代码示例
- C++ calloc()用法及代码示例
注:本文由纯净天空筛选整理自 C++ cout。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
