在本教程中,我們將借助示例了解 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
