C++的 ostream
类提供了一组用于将数据作为输出的函数和运算符。
在使用 ostream
之前,我们需要在程序中包含 <iostream>
头文件。
#include <iostream>
C++ 插入运算符 <<
要使用 ostream
将数据写入控制台,我们可以使用 cout
对象和插入运算符 <<
。
#include <iostream>
using namespace std;
int main() {
int entered_number;
// write the text "Hello World!" to the screen
cout << "Hello World!";
return 0;
}
输出
Hello World!
C++ put() 函数
ostream
的 put()
函数主要用于将字符写入控制台。例如:
#include <iostream>
using namespace std;
int main() {
char ch = 'A';
// print a character to the console
cout.put(ch);
cout<< endl ;
// print another character to the console
cout.put('C');
return 0;
}
输出
A C
C++ write() 函数
ostream
的 write()
函数通常用于将数据块写入控制台。例如:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
// create a C-string
const char* str = "Hello, World!";
// print the C-string
cout.write(str, strlen(str));
return 0;
}
输出
Hello, World!
在这里,我们使用 write()
函数将 C 字符串 Hello, World
写入了输出流。
注意:我们对 write()
函数使用了 C 字符串,因为它不适用于 C++ 的 std::string
对象。