C++ output is the text or data that is displayed to the user or written to a file. C++ provides a number of ways to output data, including the following:
std::cout << "Hello, world!" << std::endl;
std::cout << "Hello, world!" << std::endl;
printf("%d", 10);
std::ofstream my_file("my_file.txt");
my_file << "Hello, world!" << std::endl;
Example:
The following example shows how to use the cout object to output data to the console:
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
int my_variable = 10;
std::cout << my_variable << std::endl;
return 0;
}
Output:
Hello, world!
10
This example shows how to use the ofstream object to output data to a file:
#include <iostream>
#include <fstream>
int main() {
std::ofstream my_file("my_file.txt");
my_file << "Hello, world!" << std::endl;
my_file.close();
return 0;
}
This code will create a new file named my_file.txt and write the text "Hello, world!" to the file.
You can also use the \n escape sequence to insert a newline character. For example, the following statement is equivalent to the previous one:
std::cout << "Hello, world!\n";
However, it is generally considered best practice to use the std::endl object instead of the \n escape sequence. This is because the std::endl object is more portable and can be used to flush the output buffer.
Please support us by disabling your ad blocker for this website.
We rely on advertising revenue to keep the lights on and content free.
Thank you for understanding ❤️