Back to C++
2026-04-137 min read

Print Text (C++)

Learn Print Text (C++) step by step with clear examples and exercises.

Title: Print Text (C++) - A full guide for C++ Beginners

Why This Matters

Understanding how to print text in C++ is crucial for every C++ programmer. It enables you to interact with the user, display output, and debug your programs effectively. You'll learn about various methods to print text in C++, common mistakes to avoid, and practice questions to test your understanding.

Prerequisites

Before diving into printing text in C++, you should have a basic understanding of the following:

  1. C++ syntax (variables, operators, functions)
  2. Basic I/O operations (cin, cout)
  3. Control structures (if-else, loops)
  4. Understanding of data types and their representation in C++
  5. Familiarity with the standard library headers and their purpose

Core Concept

In C++, there are several ways to print text, including using the standard output stream std::cout, the printf() function, and the puts() function. We will delve deeper into each method, providing examples and explanations.

std::cout

The most commonly used method for printing text in C++ is through the standard output stream std::cout. This stream is connected to the console by default and can be used to print text with minimal setup.

#include <iostream>
int main() {
std::cout << "Hello, World!";
return 0;
}

In this example, we include the ` header, which defines the standard input and output streams. The main() function contains a single line of code that prints the string "Hello, World!" to the console using std::cout`.

Using std::cout with Variables

#include <iostream>
int main() {
int num = 42;
std::cout << "The value of num is: " << num << '\n';
return 0;
}

In this example, we demonstrate how to use std::cout to print the value of a variable. We define an integer variable num, set its value to 42, and use << operator to insert its value into the output stream.

printf()

The printf() function is another method for printing text in C++. It allows you to format your output using placeholders and conversion specifications.

#include <cstdio>
int main() {
int num = 42;
printf("The value of num is: %d\n", num);
return 0;
}

In this example, we include the ` header to access the printf() function. We define an integer variable num, set its value to 42, and use printf() to print a formatted string that includes the value of num. The conversion specification %d tells printf()` to interpret the next argument as a decimal integer.

Using printf() with Variables and Formatting

#include <cstdio>
int main() {
double pi = 3.14159265358979323846;
int age = 25;
printf("The value of Pi is: %.6f\n", pi);
printf("My name is John and I am %d years old.\n", age);
return 0;
}

In this example, we demonstrate how to use printf() with variables and formatting. We define a double variable pi containing the value of Pi and an integer variable age. The conversion specification %.6f tells printf() to print the value of pi as a floating-point number with 6 digits after the decimal point.

puts()

The puts() function is used to print a null-terminated string (i.e., a string followed by a \0 character) to the console without a newline at the end.

#include <cstring>
int main() {
char str[] = "Hello, World!";
puts(str);
return 0;
}

In this example, we include the ` header to access the puts() function. We define a character array str containing the string "Hello, World!", and use puts()` to print it to the console without a newline at the end.

Worked Example

Let's create a simple program that uses all three methods to print text:

#include <iostream>
#include <cstdio>
#include <cstring>
int main() {
std::cout << "Using std::cout:\n";
std::cout << "Hello, World!\n";

printf("Using printf():\n");
int num = 42;
printf("The value of num is: %d\n", num);

char str[] = "Using puts():";
puts(str);
char str2[] = "Hello, World!";
puts(str2);

return 0;
}

In this example, we include the necessary headers and create a program that demonstrates each method for printing text. The output should be:

Using std::cout:
Hello, World!
Using printf():
The value of num is: 42
Using puts():
Using puts():
Hello, World!

Common Mistakes

  1. Forgetting to include the necessary headers (e.g., `, , or `)
  2. Incorrectly formatting strings with printf() (e.g., using the wrong conversion specifier)
  3. Not including a null-terminator when using puts() with character arrays that don't already have one
  4. Forgetting to add a newline at the end of output with std::cout or printf() (although it is automatically added by puts())
  5. Not properly handling user input when using scanf(), which can lead to buffer overflow and security vulnerabilities
  6. Mixing up the order of arguments in printf() and scanf() functions, resulting in incorrect output or unexpected behavior

Common Mistakes - printf()

  1. Using an incorrect conversion specifier for a given data type (e.g., using %s with an integer instead of a string)
  2. Not including the appropriate modifiers (e.g., using %f without .6f for floating-point numbers with 6 digits after the decimal point)
  3. Forgetting to include spaces in formatted strings for better readability (e.g., using printf("The value of num is: %d\n", num); instead of printf("The value of num is : %d\n", num);)

Practice Questions

  1. Write a program that prints your name and age using std::cout.
  2. Modify the worked example to include a newline at the end of each output with std::cout and printf().
  3. Create a program that uses printf() to print the sum of two integers input by the user.
  4. Write a program that prints a multiplication table for a given number using puts().
  5. Modify the worked example to use scanf() to take user input and store it in variables before printing with printf().
  6. Create a program that uses both std::cout and printf() to perform calculations on two floating-point numbers, taking user input for each number.
  7. Write a program that uses puts() to display the contents of an array containing strings.
  8. Create a program that takes a string as input using scanf(), checks if it is a palindrome (reads the same backward as forward), and prints whether it is or isn't a palindrome.
  9. Write a program that uses printf() to calculate the factorial of a given number input by the user.
  10. Create a program that uses both std::cout and printf() to perform calculations on two integers, taking user input for each number, and print the results in different formats (e.g., using fixed-point notation or scientific notation).

FAQ

Q: Why is it important to include the necessary headers when printing text in C++?

A: Including the appropriate headers ensures that the necessary functions and classes are available for use in your program. Without them, you may encounter errors or be unable to compile your code.

Q: What's the difference between std::cout and printf()?

A: While both can be used to print text in C++, std::cout is a stream-based function that offers more flexibility for formatting output, while printf() uses conversion specifications to format its arguments. Stream-based functions like std::cout are generally easier to use and more intuitive for beginners.

Q: Why does puts() not add a newline at the end of its output?

A: The puts() function is designed to print a null-terminated string without adding a newline at the end. If you need a newline, use std::cout or printf(), or manually append one to your string before passing it to puts().

Q: Why should I avoid using scanf() in favor of other input methods like cin?

A: While scanf() can be useful for reading specific data types, it has several limitations and potential security vulnerabilities. For example, it can lead to buffer overflow issues if not used carefully. Modern C++ libraries like the Standard Template Library (STL) provide safer alternatives such as std::cin, which automatically handle input formatting and validation.

Q: How do I format output using std::cout?

A: To format output using std::cout, you can use manipulators like std::setw() to set the width of your output, std::fixed and std::scientific to control the floating-point notation, and std::left, std::right, and std::internal to align your output. For example:

#include <iostream>
int main() {
double pi = 3.14159265358979323846;
std::cout << "The value of Pi is: " << std::fixed << std::setprecision(6) << pi << '\n';
return 0;
}

In this example, we use std::fixed to set the floating-point notation to fixed-point and std::setprecision() to control the number of digits after the decimal point. We also demonstrate how to use std::setw() to set the width of the output.

Print Text (C++) | C++ | XQA Learn