To run already existing programs on your computer header cstdlib (C Standard General Utilities Library) must be imported:
#include <iostream>
#include <cstdlib>
Now it's easy to run, for example Windows calculator using system() function. This function help us to execute system commands:
system("calc");
And this is full source:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
system("calc");
return 0;
}
Result:
It's easy to execute multiple programs with C++. Run this code and play around with other apps you have on windows.
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
system("calc");
system("notepad");
system("calc");
return 0;
}
Run External Programs with Switch Statement
In this simple example we have information what end users need to type:
int menu = 0;
cout<< "0 for string, 1 for calc, 2 for notepad" << endl;
cout << "Please enter option: " << endl;
Then we get value with cin:
cin >> menu;
Then switch statement with 3 options and default one:
switch(menu) {
case 0:
cout << "This is just a string" << endl;
break;
case 1:
system("calc");
break;
case 2:
system("notepad");
break;
default:
cout << "Check your input" << endl;
break;
}
This is full working source:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int menu = 0;
cout<< "0 for string, 1 for calc, 2 for notepad" << endl;
cout << "Please enter option: " << endl;
cin >> menu;
switch(menu) {
case 0:
cout << "This is just a string" << endl;
break;
case 1:
system("calc");
break;
case 2:
system("notepad");
break;
default:
cout << "Check your input" << endl;
break;
}
return 0;
}
Result when input value is 0:
0 for string, 1 for calc, 2 for notepad
Please enter option:
0
This is just a string
Process returned 0 (0x0) execution time : 5.448 s
Press any key to continue.
Simple as that.
Now you know a lot of useful things in C++, but we will learn a lot more.
No comments:
Post a Comment