c++

c++输入输出流的使用方法是什么

小亿
87
2024-03-22 19:08:54
栏目: 编程语言

在C++中,可以使用iostream库中的输入输出流对象来进行输入输出操作。

  1. 输入流对象cin:用于从控制台或其他输入设备读取数据。
int num;
std::cout << "Enter a number: ";
std::cin >> num;
  1. 输出流对象cout:用于向控制台或其他输出设备输出数据。
int num = 10;
std::cout << "The number is: " << num << std::endl;
  1. 格式化输出流对象:可以使用setprecision、setw等来进行格式化输出。
double pi = 3.14159;
std::cout << std::setprecision(3) << pi << std::endl;
  1. 文件输入流对象ifstream和文件输出流对象ofstream:用于读取和写入文件。
std::ofstream outfile("example.txt");
outfile << "Hello, World!";
outfile.close();

std::ifstream infile("example.txt");
std::string line;
while (std::getline(infile, line)) {
    std::cout << line << std::endl;
}
infile.close();

需要包含头文件#include 和#include

0
看了该问题的人还看了