温馨提示×

c++ cout能处理哪些数据

c++
小樊
143
2024-11-16 08:43:51
栏目: 编程语言

C++的cout(控制台输出)是iostream库的一部分,用于向标准输出设备(通常是显示器)打印数据。cout可以处理各种基本数据类型和自定义数据类型。以下是一些常见的数据类型:

  1. 整数类型:intshortlonglong long
  2. 浮点类型:floatdoublelong double
  3. 字符类型:charsigned charunsigned char
  4. 字符串类型:std::string
  5. 指针类型:void*char*int*
  6. 其他内置类型:boolwchar_t
  7. 自定义类型:用户可以创建自己的类或结构体,并通过重载<<运算符使其支持cout输出。

例如,以下代码演示了如何使用cout输出各种数据类型:

#include <iostream> #include <string> int main() { int a = 42; double b = 3.14; char c = 'A'; std::string s = "Hello, World!"; bool d = true; std::cout << "a: "<< a << std::endl; std::cout << "b: "<< b << std::endl; std::cout << "c: "<< c << std::endl; std::cout << "s: "<< s << std::endl; std::cout << "d: "<< d << std::endl; return 0; } 

如果需要输出自定义类型,可以重载<<运算符:

#include <iostream> class MyClass { public: MyClass(int x, int y) : x_(x), y_(y) {} friend std::ostream& operator<<(std::ostream& os, const MyClass& obj); private: int x_; int y_; }; std::ostream& operator<<(std::ostream& os, const MyClass& obj) { os << "(" << obj.x_ << ", " << obj.y_ << ")"; return os; } int main() { MyClass obj(3, 4); std::cout << "obj: " << obj << std::endl; return 0; } 

0