📅  最后修改于: 2023-12-03 14:40:00.192000             🧑  作者: Mango
C++是一种高级的、静态类型的编程语言,被广泛应用于计算机程序设计和开发。输出是程序的一种基本操作,C++程序通过标准输出流(std::cout)和标准错误输出流(std::cerr)进行信息输出。本篇套装将介绍一些常见的输出技巧和用法。
C++中,输出整数可以使用std::cout流,使用流操纵符setbase()可以设置基数。
#include<iostream>
using namespace std;
int main()
{
cout << "The decimal value of 10 is " << 10 << endl;
cout << "The hexadecimal value of 15 is " << setbase(16)
<< 15 << endl;
cout << "The octal value of 10 is " << setbase(8)
<< 10 << endl;
return 0;
}
输出:
The decimal value of 10 is 10
The hexadecimal value of 15 is f
The octal value of 10 is 12
C++中,输出浮点数可以使用std::cout流,使用流操纵符setprecision()可以设置输出精度。
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
float f = 3.1415926f;
double d = 3.141592653589793;
cout << "The float value of pi is " << setprecision(3) << f << endl;
cout << "The double value of pi is " << setprecision(9) << d << endl;
return 0;
}
输出:
The float value of pi is 3.14
The double value of pi is 3.14159265
C++中,输出字符可以使用std::cout流。
#include<iostream>
using namespace std;
int main()
{
cout << "The first character of English alphabet is '"
<< 'A' << "'" << endl;
return 0;
}
输出:
The first character of English alphabet is 'A'
C++中,输出字符串可以使用std::cout流。
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s = "Hello, world!";
cout << s << endl;
return 0;
}
输出:
Hello, world!
C++中,输出布尔值可以使用std::cout流。
#include<iostream>
using namespace std;
int main()
{
bool b1 = true;
bool b2 = false;
cout << "The value of b1 is " << b1 << endl;
cout << "The value of b2 is " << b2 << endl;
return 0;
}
输出:
The value of b1 is 1
The value of b2 is 0
C++中,输出指针可以使用std::cout流。
#include<iostream>
using namespace std;
int main()
{
int *p;
int a = 10;
p = &a;
cout << "The value of p is " << p << endl;
return 0;
}
输出:
The value of p is 0x7ffca2a2b23c
C++中,进制转换可以使用std::cout流和std::bitset库。
#include<iostream>
#include<bitset>
using namespace std;
int main()
{
int a = 65;
cout << "The binary value of " << a << " is "
<< bitset<8>(a) << endl;
return 0;
}
输出:
The binary value of 65 is 01000001
C++中,输出颜色可以使用ANSI转义序列。
#include<iostream>
using namespace std;
int main()
{
cout << "\033[31mThis text color is red.\033[0m" << endl;
return 0;
}
输出:
This text color is red.
C++中,输出日期和时间可以使用std::chrono库。
#include<iostream>
#include<chrono>
#include<ctime>
using namespace std;
using namespace chrono;
int main()
{
auto start = system_clock::now();
time_t tt = system_clock::to_time_t(start);
tm* ptm = localtime(&tt);
cout << "Start time: " << put_time(ptm, "%Y-%m-%d %H:%M:%S") << endl;
auto end = system_clock::now();
tt = system_clock::to_time_t(end);
ptm = localtime(&tt);
cout << "End time: " << put_time(ptm, "%Y-%m-%d %H:%M:%S") << endl;
return 0;
}
输出:
Start time: 2022-08-17 15:25:34
End time: 2022-08-17 15:25:34
以上是C++程序输出的一些常见技巧和用法,可以根据实际需求灵活运用。