C++ offers libraries that provide numerous methods for performing input and output operations. In C++, input and output are carried out in the form of streams, which are essentially a sequence of bytes.
In C++, it is common practice to include the statement 'using namespace std;' after including the required header files. The rationale behind this practice is that all of the standard library definitions are enclosed within the 'std' namespace. Since the library functions are not defined at the global scope, we use the 'namespace std' statement to be able to use them without having to write 'STD::' before every line of code (e.g. STD::cout, etc.).
The two instances cout in C++ and cin in C++ of iostream class are used very often for printing outputs and taking inputs respectively. These two are the most basic methods of taking input and printing output in C++. To use cin and cout in C++ one must include the header file iostream in the program.
This article mainly discusses the objects defined in the header file iostream like the cin and cout.
#include <iostream>
using namespace std;
int main() {
// Declaring a character array 'string_array'char string_array[] = "Hello World!";
// Printing the string value and a message to the console
cout << string_array << " - A simple program in C++";
return 0;
}
Hello World! - A simple program in C++
Time Complexity: O(1)
Auxiliary Space: O(1)
In the program given above, the '<<' operator is known as the insertion operator. It is used to insert the value of the 'sample' string variable followed by the string "A computer science portal for geeks" into the standard output stream 'cout'. The output is then displayed on the screen.
#include <iostream>
using namespace std;
int main()
{
int userAge;
cout << "Please enter your age:";
cin >> userAge;
cout << "\nYour age is: " << userAge;
return 0;
}
18
Enter your age:
Your age is: 18
Time Complexity: O(1)
Auxiliary Space: O(1)
The program above prompts the user to input their age. The object cin is used to get input from the user, and the extraction operator(>>) is used to extract the age entered by the user, which is then stored in the integer variable age.
#include <iostream>
using namespace std;
int main()
{
// Outputting an error message using cerr
cerr << "An error has occurred." << endl;
return 0;
}
An error has occurred.
Time Complexity: O(1)
Auxiliary Space: O(1)
#include <iostream>
using namespace std;
int main()
{
clog << "A warning occurred";
return 0;
}
A warning occurred
Time Complexity: O(1)
Auxiliary Space: O(1)
70 videos|45 docs|15 tests
|
|
Explore Courses for EmSAT Achieve exam
|