1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <iostream> #include <string> #include <cstdlib> using namespace std; int main() { string command; cout << "Simple Shell - Type 'exit' to quit" << endl; while (true) { cout << "> "; getline(cin, command); // Read user input if (command == "exit") { break; // Exit the loop and terminate the shell } // Execute the command using system() int result = system(command.c_str()); // Check if the command execution was successful if (result != 0) { cerr << "Error: Command failed with return code " << result << endl; } } return 0; } |
Explanation
- Headers:
<iostream>
: For input and output operations.<string>
: To use thestd::string
class.<cstdlib>
: For thesystem()
function.
- Main Function:
- Initialization:
- Displays a welcome message indicating the shell’s start and how to exit.
- Command Loop:
- Uses an infinite
while (true)
loop to continuously prompt the user for input. getline(cin, command)
: Reads a full line of input from the user and stores it in thecommand
string.
- Uses an infinite
- Exit Condition:
- If the user types
exit
, the loop breaks, and the shell terminates.
- If the user types
- Command Execution:
system(command.c_str())
: Executes the command entered by the user. Thec_str()
method converts thestd::string
to a C-style string (const char*
), which is required by thesystem()
function.- Checks the return value of
system()
. A non-zero return value indicates that the command failed, and an error message is printed.
- Initialization:
Notes:
- This simple shell uses the
system()
function, which executes commands as if they were typed into the command line. It is useful for learning and basic use but has security and portability considerations. - The shell can execute any command that the underlying system’s shell can handle (e.g.,
ls
,dir
,mkdir
, etc.). - For real-world applications, consider using more secure and sophisticated methods for command execution and shell interaction. This example is intended for educational purposes to illustrate basic shell functionality.