Monday, 21 January 2013

OOP344 exercise -Week2

 1. write 4 command line programs to do
$ add num num<ENTER>
$ sub num num<ENTER>
$ mul num num<ENTER>
$ div num num<ENTER>


// command.cpp

#include "stdlib.h"
#include <iostream>

using namespace std;
int main(int argc,char* argv[]){  
 char comm[100]="calculate";
 int i;
 if(argc < 3)                
 {
  cout <<"ERROR: Please enter the command followed by two numeric at least...\n" << endl;
  return 1;
 }
 
 for (i = 0; i < argc; argv++, i++){
  strcat(comm, " ");
  strcat(comm,*argv);
 }
 system(comm);
   return 0;
      
}
// after compile command.cpp, copy "command.exe" file to "add.exe, sub.exe, mul.exe,div.exe"; or alias command in the Linux bash shell.

//calculate.cpp
#include "ctype.h"
#include <iostream>

using namespace std;
void cal(int argn,char* argvc[]);

void results(double);

int main(int argc,char* argv[]){  
 if (argc > 3) 
  cal(argc,argv);
 else
  cout << "ERROR: Invaild Command."<<endl;
 return 0;
      
}
void cal(int argn,char* argvc[]){
 double re = 0;
 int i;
 if ( strcmp(*(argvc+1),"add")==0){
  for( i = 2; i < argn ; i++){
   if (i > 2) cout << " + ";
   if (i > 0) cout << argvc[i];
   re += atoi(argvc[i]);
  }
 }
 else if ( strcmp(*(argvc+1),"sub")==0){
  re = (atoi(argvc[2])*2);
  for( i = 2; i < argn ; i++){
   if (i > 2) cout << " - ";
   if (i > 0) cout << argvc[i];
   re -= atoi(argvc[i]);
  }
 }
 else if ( strcmp(*(argvc+1),"mul")==0){
  re = 1;
  for( i = 2; i < argn ; i++){
  if (i > 2) cout << " * ";
  if (i > 0) cout << argvc[i];
   re *= atoi(argvc[i]);
  }
 }
 else if ( strcmp(*(argvc+1),"div")==0){
  re = atoi(argvc[2]);
  re *= re;
  for( i = 2; i < argn ; i++){
   if (i > 2) cout << " / ";
   if (i > 0) cout << argvc[i];
   re /= atoi(argvc[i]);
  }
 }  
 results(re);
}

void results(double re){
 cout << " = " << re << endl;
}



2. write a program to show the content of an Operating system environment variable
$ pnenvr path
The output will be either the "content" of path variable or "not found" if the environment variable does not exist.

//Show the content of an Os environment variable

#include <string>
#include <iostream> 
#include <cctype> 
#include <algorithm> 
using namespace std; 
int main(int argc, char* argv[], char* env[]){ 
 int i; 
 string s1(argv[1]); 
 string s2; 
 string token("="); 
 bool find=false; 
  
 s1.append(token); 
  
 transform(s1.begin(), s1.end(), s1.begin(), ::toupper); 
 for(i=0;env[i] != 0;i++){ 
  s2=env[i]; 
  transform(s2.begin(), s2.end(), s2.begin(), ::toupper); 
  s2=s2.substr(0,s1.length()); 
   
  if (s2 == s1) { 
   find=true; 
   cout << env[i] << endl; 
   break; 
  } 
 }
 if (find != true)  
  cout << "Not found" ;
 return 0;
} 

No comments:

Post a comment