In C++, you can output text and values to the console using the cout
statement. Here's how it works:
- Outputting Text: To output text, simply put the text inside quotes and pass it to the
cout
statement. For example:
cout << "Hello, world!" << endl;
This will output the text "Hello, world!" to the console.
- Outputting Values: To output values, you can use the
<<
operator to concatenate values with text. For example:
int age = 25;
cout << "I am " << age << " years old." << endl;
This will output the text "I am 25 years old." to the console.
- Formatting Output: You can also format the output using various manipulators. For example:
double pi = 3.14159;
cout << "The value of pi is: " << fixed << setprecision(2) << pi << endl;
This will output the text "The value of pi is: 3.14" to the console. The fixed
manipulator specifies that the output should have a fixed number of decimal places, and the setprecision
manipulator sets the number of decimal places to 2.
- Using Escape Characters: You can also use escape characters to output special characters, such as newlines or tabs. For example:
cout << "First line\nSecond line\tTabbed text" << endl;
This will output the text "First line", followed by a newline, "Second line", followed by a tab, and "Tabbed text" to the console.
Comments