cout 是 C++ 标准库中的一个对象,它表示标准输出流(通常是屏幕)。cout 提供了许多有用的功能,例如:
- 输出数据类型:
cout可以输出各种数据类型的数据,如整数、浮点数、字符、字符串等。例如:
#include <iostream>
using namespace std;
int main() {
int a = 42;
double b = 3.14;
char c = 'A';
string s = "Hello, World!";
cout << "a: "<< a << endl;
cout << "b: "<< b << endl;
cout << "c: "<< c << endl;
cout << "s: "<< s << endl;
return 0;
}
- 格式化输出:
cout支持使用流操作符(如<<)和格式说明符(如%d、%.2f等)进行格式化输出。例如:
#include <iostream>
using namespace std;
int main() {
int a = 42;
double b = 3.1415926;
cout << "a: %d, b: %.2f"<< a << b << endl;
return 0;
}
- 输出到文件:通过重定向标准输出流,可以将
cout的输出重定向到文件中。例如:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outfile("output.txt");
if (outfile.is_open()) {
cout << "This output will be written to output.txt" << endl;
outfile.close();
} else {
cout << "Unable to open file" << endl;
}
return 0;
}
- 使用命名空间:为了避免命名冲突,可以使用
std命名空间来访问cout。例如:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
总之,cout 是 C++ 中一个非常实用的工具,可以用于在控制台输出各种类型的数据,并支持格式化输出、文件输出和使用命名空间等功能。

便宜VPS测评








