Welcome to our deep dive into C++ Output! In this lesson, we'll explore various ways to output data using C++, making your code more informative and interactive. Let's get started! šÆ
In C++, we use the std::cout function to display output on the console. std::cout belongs to the <iostream> library and is an ostream object representing the standard output stream.
#include <iostream>
int main() {
std::cout << "Hello, World!";
return 0;
}In the above example, we're including the <iostream> library and using the std::cout function to print "Hello, World!" on the console. ā
To print a variable, we simply include the variable name within the std::cout function.
#include <iostream>
int main() {
int age = 20;
std::cout << "My age is " << age << ".";
return 0;
}In the example above, we're declaring an integer variable called age, then using std::cout to print "My age is " followed by the value of the age variable.
std::cout š”You can also use basic operators, such as +, -, *, and /, within the std::cout function to perform calculations and display the results.
#include <iostream>
int main() {
int a = 5;
int b = 3;
std::cout << "The sum of " << a << " and " << b << " is " << (a + b) << ".";
return 0;
}In this example, we're using the + operator to calculate the sum of a and b and then printing the result using std::cout.
C++ provides formatted output to make it easier to display specific data types and perform manipulations.
std::endl š”The std::endl manipulator inserts a newline character and flushes the output buffer. It is often used to print a newline after each output.
#include <iostream>
int main() {
int a = 5;
int b = 3;
std::cout << "The sum of " << a << " and " << b << " is " << (a + b) << std::endl;
std::cout << "My favorite number is 42.";
return 0;
}In this example, we're using std::endl to print a newline after the sum and then printing a separate statement on the same line.
std::setw and std::setprecision š”std::setw sets the width of the field in which the output is displayed, while std::setprecision sets the number of digits after the decimal point.
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.14159265358979323846;
std::cout << std::setw(10) << std::setprecision(6) << pi << std::endl;
return 0;
}In this example, we're using std::setw and std::setprecision to format the output of the pi variable.
Which header file should be included to use the `std::cout` function?
By the end of this lesson, you should have a solid understanding of output operations in C++. Happy coding! š