📜  在列 c++ 中打印(1)

📅  最后修改于: 2023-12-03 15:07:58.113000             🧑  作者: Mango

在C++中打印

在C++中打印可以通过使用输出流对象和相关操作符来实现。输出流对象包括cout, cerr和clog。

输出操作符

输出操作符<<可以用来输出各种数据类型,也可以用于字符数组和指针。

以下是几个例子:

int x = 10;
cout << "x = " << x << endl;

char str[] = "hello";
cout << "str[] = " << str << endl;

int *ptr = &x;
cout << "ptr = " << ptr << endl;

输出:

x = 10
str[] = hello
ptr = 0x7ffeefbff3d8

注意,当使用输出操作符<<输出字符数组时,会输出整个数组,而不是字符串。

格式化输出

C++中可以使用iomanip库和相关操作符来进行格式化输出。

以下是几个例子:

int x = 10;
double y = 3.1415926;

cout << setw(10) << x << endl;
cout << fixed << setprecision(3) << y << endl;
cout << hex << x << endl;

输出:

        10
3.142
a

setw(n)可以设置输出宽度为n个字符,setprecision(n)可以设置小数精度为n位,hex可以把输出转换为16进制。

结束输出行

C++中可以使用endl操作符来结束当前输出行。

cout << "hello, world!" << endl;

输出:

hello, world!
总结

C++中有多种方式可以实现打印输出。输出操作符<<可以输出各种数据类型,而且可以用于字符数组和指针。格式化输出可以通过iomanip库和相关操作符实现。结束输出行可以使用endl操作符。