在C++中,cout是一个标准输出流对象,用于将数据输出到控制台。cout对象提供了<<操作符重载,可以用来将各种类型的数据输出到控制台。
cout输出语句的一般规则如下:
<<操作符,将字符串放置在<<操作符的右侧。输出变量:使用<<操作符,将变量放置在<<操作符的右侧。输出多个变量或字符串:可以使用多个<<操作符,将字符串和变量依次放置在<<操作符的右侧。输出特定格式的数据:可以使用控制符来指定输出的格式,例如使用setw()函数来设置输出的宽度,使用setprecision()函数来设置输出浮点数的精度等。以下是一些示例:
#include <iostream>#include <iomanip>int main() { int num = 10; float pi = 3.14159; std::string str = "Hello, World!"; // 输出字符串 std::cout << "This is a string." << std::endl; // 输出变量 std::cout << num << std::endl; // 输出多个变量和字符串 std::cout << "The value of num is: " << num << std::endl; // 输出特定格式的数据 std::cout << "The value of pi is: " << std::setprecision(3) << pi << std::endl; return 0;}运行以上代码将输出:
This is a string.10The value of num is: 10The value of pi is: 3.14 
