This C++ program demonstrates how to use the system()
function to execute an external system command from within a C++ program. Specifically, it executes the date
command, which prints the current date and time on the system.
#include <iostream>
using namespace std;
int main() {
int n;
// Execute the 'date' system command and print its return value
cout << system("date") << endl;
return 0;
}
int main() {
int n;
// Execute the 'date' system command and print its return value
cout << system("date") << endl;
return 0;
}
int main() {
is the main function where the program execution begins. int n;
declares an integer variable n
. In this program, n
is declared but not used.
cout << system("date") << endl;
executes the date
command using the system()
function. This command displays the current date and time. The cout << ... << endl;
prints the return value of the system()
function call. The system()
function returns an integer value, which is typically the exit status of the command. Printing it is usually not very meaningful in this context.
return 0;
returns 0 to indicate that the program ended successfully.
When you run this program, the output will depend on the operating system. On most systems, the date
command will print the current date and time.
For example, on a Unix-like system (Linux, macOS), the output might look something like:
Wed Jun 27 15:23:42 PDT 2024
0
On a Windows system, the date
command might prompt for input or display the date in a different format:
The current date is: 06/27/2024
Enter the new date: (mm-dd-yy)
0
In both cases, the 0
at the end is the return value of the system()
function, indicating successful execution.
To make the program more meaningful and avoid printing the return value of the system()
function, we can separate the command execution and output:
#include <iostream>
using namespace std;
int main() {
// Execute the 'date' system command
system("date");
return 0;
}
n
.system("date")
command without printing its return value. This focuses the program on executing the command and displaying its output directly to the console.