-
-
Notifications
You must be signed in to change notification settings - Fork 1
Output
C++ is a way to make cool programs that do lots of things. Output in C++ is when we show the program's results in a way that makes sense. We can show it on the computer screen, in a file, or somewhere else.
Cout
is the most common way of outputting in C++. To use cout
, we need to include the iostream
header file.
There are also other ways of outputting in C++. Fstream
is used to write data to a file. Ofstream
is used to write data to a file in an output mode. And stringstream
is used to write data to a string.
Outputting in C++ is important because it helps us debug and test programs. We can make sure our program is working right.
#include <iostream>
//Header File Library
int main()
//Main Function
{
//curly brace
std::cout << "Hello World!";
//std is using the Standard Library
return 0;
//Program returns an integer (number) 0 when program is executed completely
}
//curly brace
#include <iostream>
//Header File Library#include <fstream>
//Header File Library
int main()
//Main Function
{
//curly braces
std::ofstream myFile("data.txt");
//Create an ofstream object named myFile
if (myFile.is_open())
//Check to see if the file was opened
{
myFile << "Hello World!" << std::endl;
//Write "Hello World!" to the file`myFile.close();` //Close the file
}
else
`std::cout << "Unable to open file";` //Print error message if file was not opened
return 0;
}
This code creates a file named "data.txt" and writes the string "Hello World!" to the file. If the file is unable to open, it will print "Unable to open file" to the console.