C语言中的cout是用于输出的流对象,它位于<iostream>头文件中,下面是关于cout的详细用法:

(图片来源网络,侵删)
1、引入头文件
#include <iostream>
2、使用cout输出基本数据类型
| 数据类型 | 输出方式 |
| int | cout << x; |
| float | cout << x; |
| double | cout << x; |
| char | cout << x; |
| bool | cout << x; |
| wchar_t | cout << x; |
| string | cout << x; |
3、使用cout输出字符串常量和变量
| 字符串常量 | 输出方式 |
| 直接输入 | cout << "hello"; |
| 转义字符 | `cout << "hello" << ‘
‘;` |
| 变量 | string str = "hello"; cout << str; |
4、使用cout输出格式化字符串
setw()设置宽度
setfill()设置填充字符
setprecision()设置小数位数
fixed和scientific设置显示格式
left, right, internal设置对齐方式
示例:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
double num = 3.1415926;
cout << fixed << setprecision(2) << num << endl; // 输出:3.14,保留两位小数
cout << setw(8) << left << num << endl; // 输出:3.14,左对齐,宽度为8
return 0;
}
5、使用endl换行并刷新缓冲区
cout << "hello" << endl; // 输出:hello,换行并刷新缓冲区
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。



评论(0)