The cout
object, together with the <<
operator, is used to display output values and print text to the standard output device. The cout
object is defined in the iostream
header file, and is part of the std
standard namespace. You can use the cout
object in your program as many times as you desire.
To use the cout
object, you must include the iostream
class into your program by adding the
statement to the beginning of your program.
The syntax of the cout
object is:
or
Or if you add a statement showing that you are using the std
namespace (see alternative examples below), then you can shorten the syntax to:
or
#include <iostream>
int main () {
// print value to output device
std ::cout << "Hello World!" ;
// return normal
return 0;
}
Alternatively, you can specify using the namespace std
(which stands for standard) with
statement, which allows you to shorten the function call to cout
instead of having to type out std::cout
each time you want to output a value, for example:
#include <iostream>
using namespace std ;
int main () {
// print value to output device
cout << "Hello World!"
// return normal
return 0;
}
The cout
can output/print values as well as strings, such as in the following example the value of an integer is printed to the console window:
#include <iostream>
using namespace std ;
int main () {
// instantiate an integer type variable and assign it a value of 24
int tempCount = 24;
// print value to output device
cout << "Value of tempCount is " << tempCount ;
// return normal
return 0;
}
You can also add an End Line command ( endl
) to the cout
statement, so that it prints a new line return at that location:
#include <iostream>
using namespace std ;
int main () {
// add endl to end of string, and print value to output device
cout << "Hello World!" << endl ;
// add endl to middle and end of string, to produce multiline text output, and print value to output device
cout << "Hello World!" << endl << "This is a test." << endl ;
// return normal
return 0;
}
Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.
About | Contact Us | Privacy | Terms & Conditions | © 2024 - T&J Divisions, LLC, All Rights Reserved |