C++的ostream应该如何使用
C++中的ostream是用于输出数据的流,它可以将数据写入到文件或者屏幕上。以下是使用ostream的一些示例:
- 输出到屏幕上
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 0;
}
- 输出到文件中
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream outfile("output.txt");
outfile << "Hello World!" << endl;
outfile.close();
return 0;
}
- 格式化输出
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi = 3.14159265358979323846;
cout << fixed << setprecision(2) << pi << endl;
return 0;
}
- 输出对象
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
Person(string n, int a) : name(n), age(a) {}
};
ostream& operator<<(ostream& os, const Person& p) {
os << "Name: " << p.name << ", Age: " << p.age;
return os;
}
int main() {
Person person("John", 25);
cout << person << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/bykv 著作权归作者所有。请勿转载和采集!