C++ input and output basics

Input and output are among the first concepts every C++ learner meets. They seem simple at first, but they are fundamental because nearly every real program needs to read something, display something, or store something in a file.

Console Output with cout

The standard output stream is usually accessed through cout.

#include <iostream>
using namespace std;

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

Console Input with cin

You can read user input with cin.

#include <iostream>
using namespace std;

int main() {
    string name;
    cin >> name;
    cout << "Hello, " << name << endl;
    return 0;
}

A Common Beginner Mistake

Using cin >> name only reads input until the first space. If you want a full line such as Thanh Nguyen, use getline instead.

File Output

C++ also supports file streams for reading and writing files.

#include <fstream>
using namespace std;

int main() {
    ofstream file("output.txt");
    file << "Stored text" << endl;
}

Why This Matters

Once you understand input and output, you can start building tools that interact with users, process data files, or write logs. That is the point where a learning exercise starts becoming a real program.

Final Thoughts

C++ input and output are simple to begin with, but they open the door to practical programming. Mastering these basics makes it much easier to move on to file processing, configuration handling, and larger applications.

2 Comments

Leave a Comment