输出整数:
#include
int main() {
int num = 10;
std::cout << "The number is: " << num << std::endl;
return 0;
}
输出浮点数:
#include
int main() {
double pi = 3.14159;
std::cout << "The value of pi is: " << pi << std::endl;
return 0;
}
输出字符串:
#include
int main() {
std::string greeting = "Hello, world!";
std::cout << "The greeting is: " << greeting << std::endl;
return 0;
}
输出字符:
#include
int main() {
char letter = 'A';
std::cout << "The letter is: " << letter << std::endl;
return 0;
}
输出布尔值:
在 C++ 中,布尔值 true 和 false 会自动转换为整数 1 和 0。因此,可以直接输出。
#include
int main() {
bool flag = true;
std::cout << "The flag is: " << flag << std::endl; // 输出 1 (true) 或 0 (false)
return 0;
}
格式化输出:可以使用流操作符 << 与各种格式化函数(如 std::setw, std::setprecision 等)结合使用,以控制输出的格式。例如:
#include
#include
using namespace std; // 使用 std 命名空间以简化代码。这通常在小型程序中是可接受的,但在大型程序中可能会引起冲突。最好明确指定命名空间。
int main() {
double num = 123.456789;
cout << setw(10) << setprecision(4) << num << endl; // 设置宽度为10,精度为4,然后输出数字。这会输出 " 123.46"(前面有五个空格)。
return 0;
}