C++中的cout对象是ostream类的对象。它在iostream头文件中定义。它用于显示输出到标准输出设备,即监视器。它与标准C输出流stdout相关联。使用插入运算符(<<)将需要在屏幕上显示的数据插入到标准输出流(cout)中。
程序1:
下面是实现cout对象的C++程序:
C++
// C++ program to illustrate the use
// of cout object
#include
using namespace std;
// Driver Code
int main()
{
// Print standard ouput
// on the screen
cout << "Welcome to GFG";
return 0;
}
C++
// C++ program to illustrate printing
// of more than one statement in a
// single cout statement
#include
using namespace std;
// Driver Code
int main()
{
string name = "Akshay";
int age = 18;
// Print multiple variable on
// screen using cout
cout << "Name : " << name << endl
<< "Age : " << age << endl;
return 0;
}
C++
// C++ program to illustrate the use
// of cout.write() and cout.put()
#include
using namespace std;
// Driver Code
int main()
{
char gfg[] = "Welcome at GFG";
char ch = 'e';
// Print first 6 characters
cout.write(gfg, 6);
// Print the character ch
cout.put(ch);
return 0;
}
C++
// C++ program toillustrate the use
// of cout.precision()
#include
using namespace std;
// Driver Code
int main()
{
double pi = 3.14159783;
// Set precison to 5
cout.precision(5);
// Print pi
cout << pi << endl;
// Set precision to 7
cout.precision(7);
// Print pi
cout << pi << endl;
return 0;
}
输出:
Welcome to GFG
注意:使用带有cout的插入运算符(<<)可以打印多个变量。
程式2:
下面是实现上述方法的C++程序:
C++
// C++ program to illustrate printing
// of more than one statement in a
// single cout statement
#include
using namespace std;
// Driver Code
int main()
{
string name = "Akshay";
int age = 18;
// Print multiple variable on
// screen using cout
cout << "Name : " << name << endl
<< "Age : " << age << endl;
return 0;
}
输出:
Name : Akshay
Age : 18
cout语句也可以与某些成员函数一起使用:
- cout.write(char * str,int n):打印从str读取的前N个字符。
- cout.put(炭&CH):打印存储在字符ch的字符。
- cout.precision(int n):使用浮点值时,将小数精度设置为N。
程序3:
以下是cout.write()和cout.put()的成员函数的实现:
C++
// C++ program to illustrate the use
// of cout.write() and cout.put()
#include
using namespace std;
// Driver Code
int main()
{
char gfg[] = "Welcome at GFG";
char ch = 'e';
// Print first 6 characters
cout.write(gfg, 6);
// Print the character ch
cout.put(ch);
return 0;
}
输出:
Welcome
计划4:
下面是C++程序,用于说明cout.precision()的用法:
C++
// C++ program toillustrate the use
// of cout.precision()
#include
using namespace std;
// Driver Code
int main()
{
double pi = 3.14159783;
// Set precison to 5
cout.precision(5);
// Print pi
cout << pi << endl;
// Set precision to 7
cout.precision(7);
// Print pi
cout << pi << endl;
return 0;
}
输出:
3.1416
3.141598
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。