C++ Basic Input/Output

Hello there, future C++ programmers! Today, we're going to dive into the exciting world of input and output in C++. Don't worry if you've never written a line of code before – we'll start from the very beginning and work our way up. By the end of this tutorial, you'll be amazed at how much you can do with just a few lines of C++ code!

C++ Basic Input/Output

I/O Library Header Files

Before we can start printing messages to the screen or reading input from the user, we need to include the necessary header files. In C++, input and output operations are handled by the iostream library.

Let's start with a simple example:

#include <iostream>

int main() {
    // Your code will go here
    return 0;
}

This is the basic structure of a C++ program. The #include <iostream> line tells the compiler to include the iostream library, which gives us access to input and output functionality.

The Standard Output Stream (cout)

Now, let's learn how to display text on the screen. In C++, we use cout (pronounced "see-out") to send output to the console.

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!";
    return 0;
}

When you run this program, it will display "Hello, World!" on the screen. Let's break it down:

  • cout is the standard output stream object.
  • The << operator is used to send data to cout.
  • The text inside the double quotes is called a string literal.

You can also use cout to print multiple items:

cout << "My name is " << "Alice" << " and I am " << 25 << " years old.";

This will output: "My name is Alice and I am 25 years old."

Adding a New Line

To move to a new line after output, you can use the endl manipulator or the \n character:

cout << "First line" << endl;
cout << "Second line\n";
cout << "Third line" << '\n';

The Standard Input Stream (cin)

Now that we can output text, let's learn how to get input from the user. We use cin (pronounced "see-in") for this purpose.

#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "How old are you? ";
    cin >> age;
    cout << "You are " << age << " years old!" << endl;
    return 0;
}

In this example:

  • We declare an integer variable age to store the user's input.
  • We use cout to prompt the user for their age.
  • cin >> age reads an integer from the user and stores it in the age variable.
  • Finally, we use cout to display the result.

You can also read multiple inputs:

string name;
int age;
cout << "Enter your name and age: ";
cin >> name >> age;
cout << "Hello, " << name << "! You are " << age << " years old." << endl;

The Standard Error Stream (cerr)

While cout is great for normal output, sometimes we need to display error messages. That's where cerr comes in. It's similar to cout, but it's specifically meant for error messages.

#include <iostream>
using namespace std;

int main() {
    int denominator = 0;
    if (denominator == 0) {
        cerr << "Error: Cannot divide by zero!" << endl;
    }
    return 0;
}

Using cerr helps distinguish between normal output and error messages, which can be crucial when debugging your programs.

The Standard Log Stream (clog)

Lastly, we have clog, which is used for logging messages. It's similar to cerr, but it might be buffered, meaning the output might not appear immediately.

#include <iostream>
using namespace std;

int main() {
    clog << "This is a log message." << endl;
    return 0;
}

In practice, clog isn't used as frequently as cout and cerr, but it's good to know it exists.

Formatting Output

Now that we've covered the basics, let's look at some ways to format our output to make it look nicer.

Setting Field Width

You can use the setw manipulator to set the width of a field:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    cout << setw(10) << "Name" << setw(5) << "Age" << endl;
    cout << setw(10) << "Alice" << setw(5) << 25 << endl;
    cout << setw(10) << "Bob" << setw(5) << 30 << endl;
    return 0;
}

This will produce a nicely aligned output:

     Name  Age
    Alice   25
      Bob   30

Precision for Floating-Point Numbers

For floating-point numbers, you can control the precision using setprecision:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double pi = 3.14159265359;
    cout << "Default pi: " << pi << endl;
    cout << "Pi to 4 decimal places: " << fixed << setprecision(4) << pi << endl;
    return 0;
}

Output:

Default pi: 3.14159
Pi to 4 decimal places: 3.1416

Summary of I/O Stream Objects and Manipulators

Here's a handy table summarizing the I/O stream objects and manipulators we've learned:

Object/Manipulator Description Example
cout Standard output stream cout << "Hello";
cin Standard input stream cin >> variable;
cerr Standard error stream cerr << "Error!";
clog Standard log stream clog << "Log message";
endl End line cout << "Hello" << endl;
setw Set field width cout << setw(10) << "Name";
setprecision Set floating-point precision cout << setprecision(2) << 3.14159;

And there you have it! You've just learned the basics of input and output in C++. Remember, practice makes perfect, so don't be afraid to experiment with these concepts. Try combining them in different ways, and soon you'll be writing complex programs with ease.

Happy coding, and may your outputs always be as expected and your inputs always valid!

Credits: Image by storyset