System() function in C++
As a part of the c/c+ standard library, the system() function passes commands to be executed by the operating system’s command processor or terminal and returns the completed command. We need to use <cstdlib> while using the system commands. As there are few commands that are linked with the system function.
There are many commands that can be used with the system keyword and one of them is,
System(“date”)
Example:1
#include <iostream>
using namespace std;
int main(){
//system function is used to print the date
system("date");
}
Output:
Explanation:
In the above code, we have used the system function to print the current date. As we can see, when we use the system(“date”), the then-current date is printed in the output console in the form of dd-mm-yy.
Example-2: Code for changing the color of the cmd
#include <iostream>
using namespace std;
int main(){
system("color a");
}
Explanation:
In the above code, we have used the system function to change the color of the output terminal. By using the “color a, “ the output terminal color will be changed to pink.
There are a few commands that are present in the Linux
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
// Try the "ls -l" command from your Linux / Mac machine
int ret = system("ls -l > test.txt");
return 0;
}
Output:
System(“pause”);
The system (“pause”) will pause the program until we press any key. When the pause statement executes, the os will pause the program.
Example:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
for (int i=0; i<10; i++) {
cout << "i = " << i << endl;
if (i == 5) {
// Call the pause command
cout << "Calling the pause command\n";
system("pause");
cout << "pause program terminated. Resuming...\n";
}
}
return 0;
}
Output:
Explanation:
In the above code, we have used the pause command in the system function. We can observe a pause in the for loop, which will be resumed when we press any key then the remaining part of the code will be executed. The two statements Calling the pause command and pause program terminated. Resuming... will be displayed until the key is pressed.