温馨提示×

C++之 ostream详细用法

c++
小云
264
2023-09-02 05:07:06
栏目: 编程语言

ostream 是 C++ 标准库中用于输出的基类,它定义了输出流对象的基本行为和接口。ostream 是一个抽象类,不能直接实例化,常常通过其派生类 ostream 对象来实现具体的输出操作。

以下是 ostream 类的一些重要成员函数和用法:

  1. operator<< 操作符:ostream 类重载了左移运算符,可以使用它向流中插入各种类型的数据。例如:
#include <iostream>
int main() {
int num = 10;
std::cout << "The number is: " << num << std::endl;
double pi = 3.14159;
std::cout << "The value of pi is: " << pi << std::endl;
return 0;
}
  1. put 函数:put 函数用于将一个字符写入到流中。例如:
#include <iostream>
int main() {
std::cout.put('H');
std::cout.put('e');
std::cout.put('l');
std::cout.put('l');
std::cout.put('o');
std::cout.put('\n');
return 0;
}
  1. write 函数:write 函数将指定长度的字节序列写入到流中。例如:
#include <iostream>
int main() {
const char* str = "Hello, World!";
std::cout.write(str, 13);
return 0;
}
  1. flush 函数:flush 函数用于刷新流,将流中的数据立即写入到输出设备中。例如:
#include <iostream>
int main() {
std::cout << "This is some text.";
std::cout.flush();
std::cout << "This will be written immediately.";
return 0;
}
  1. widthfill 函数:width 函数用于设置输出字段的宽度,fill 函数用于设置填充字符。例如:
#include <iostream>
int main() {
std::cout.width(10);
std::cout.fill('*');
std::cout << 42 << std::endl;
return 0;
}

以上是 ostream 类的一些常用成员函数和用法,通过它们可以实现各种形式的输出操作。可以根据具体需求和情况选择适当的成员函数来完成输出任务。

0