The cout function in C is used to output data to the console or other output streams. The usage method is: cout << "output content" << endl;, where "output content" can be characters String, number, variable or expression, endl means line break. cout also supports custom formatted output, and you can use format specifiers to control the format of the output data, such as %d for integers, %f for floating point numbers, and %s for strings. In addition, cout can redirect output to a file or other output stream, and can also set the output precision.
Usage of cout in C
cout is used in C programming language to output data to the console or Standard library functions for other output streams. It belongs to the iostream header file and needs to be included before use.
Usage:
The basic syntax of cout is as follows:
<code class="cpp">cout << "输出内容" << endl;</code>
Example:
<code class="cpp">#include <iostream> using namespace std; int main() { cout << "你好,世界!" << endl; cout << "我的年龄是:" << 25 << endl; return 0; }</code>
Output:
<code>你好,世界! 我的年龄是:25</code>
Custom formatted output:
cout Format specifiers can be used to control the format of the output data. The most commonly used specifiers are:
Specifier | Description |
---|---|
Integer | |
Floating point number | |
String |
<code class="cpp">#include <iostream>
using namespace std;
int main() {
int age = 25;
float height = 1.75;
cout << "我的年龄是 %d,身高是 %f 米。" << endl;
return 0;
}</p>Output:<p><strong><pre class="brush:php;toolbar:false"><code>我的年龄是 25,身高是 1.75 米。</code>
cout can be redirected to a file or other output stream, for example: <code class="cpp">ofstream myFile("output.txt");
cout.rdbuf(myFile.rdbuf());</code>
cout You can use the setprecision() method to set the output precision of floating point numbers. For example: <code class="cpp">cout << fixed << setprecision(2) << 3.14159;</code>
cout always flushes its buffer , so the output will be displayed immediately.
The above is the detailed content of How to use cout in c++. For more information, please follow other related articles on the PHP Chinese website!