How Do You Read in Keyboard Input from a User and Invoke a Unix Shell Command with a C++ Program?

Problem scenario
You want to see how C++ works.  You want to read in user input from the keyboard and have the C++ program run a bash command.  How do you do this?

Solution
Compile this code (e.g., as a file named "test.cpp" with "g++ test.cpp") and run it (e.g., ./a.out):

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main ()
{
  int i;
  string x;
  cout << "Please enter an integer value: ";
  cin >> i;
  cout << "The value you entered is " << i;
  cout << " and its double is " << i*2 << ".\n";
  x = system("/bin/date");
  return 0;
}

Leave a comment

Your email address will not be published. Required fields are marked *