C++ Input and Output I/O
In C++, input and output operations are performed using the cin
and cout
streams.
Standard Output (cout)
The standard output in C++ is represented by the cout
stream. The cout
stream is used to output data to the screen. The cout
stream is declared in the iostream
library, and it is used along with the insertion operator <<
.
Here's an example of using cout
to output data to the screen:
1#include <iostream> 2 3int main() 4{ 5 std::cout << "Hello World!" << std::endl; 6 return 0; 7}
In the above code, the text "Hello World!" is output to the screen using the cout
stream and the insertion operator <<
. The std::endl
manipulator is used to insert a newline character after the output.
Standard Input (cin)
The standard input in C++ is represented by the cin
stream. The cin
stream is used to input data from the keyboard. The cin
stream is also declared in the iostream
library, and it is used along with the extraction operator >>
.
Here's an example of using cin
to input data from the keyboard:
1#include <iostream> 2 3int main() 4{ 5 int x; 6 std::cout << "Enter a number: "; 7 std::cin >> x; 8 std::cout << "You entered: " << x << std::endl; 9 return 0; 10}
In the above code, the user is prompted to enter a number using the cout
stream. The input is then stored in the variable x
using the cin
stream and the extraction operator >>
. The input value is then output to the screen using the cout
stream.
using namespace std
Include using namespace std;
statement at top to avoid using cin
and count
without std::
1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 int x; 7 cout << "Enter a number: "; 8 cin >> x; 9 cout << "You entered: " << x << endl; 10 return 0; 11}
In the above example, the line using namespace std;
allows us to use the cin
and cout
streams without having to qualify them with std::
. This line makes all the symbols in the std
namespace available to our code.