Tuesday 15 January 2013



WEEK 2: Command Line Programs


$ add num num<ENTER>

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

int main(int argc, char* argv[]) {

  int sum;
if (argc==3) {    //only accept three parameters
sum = atoi(argv[1]) + atoi(argv[2]);
cout << "The sum of the two numbers is: " << sum << endl;
} else {
cout << "Enter 2 valid parameters after the program name" << endl;
}
return 0;
}



$ sub num num<ENTER>

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

int main(int argc, char* argv[]) {

  int diff;
if (argc==3) {    //only accept three parameters
diff = atoi(argv[1]) - atoi(argv[2]);
cout << "The difference between of the two numbers is: " << diff << endl;
} else {
cout << "Enter 2 valid parameters after the program name" << endl;
}
return 0;
}




$ mul num num<ENTER>

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

int main(int argc, char* argv[]) {

  int total;
if (argc==3) {    //only accept three parameters
total = atoi(argv[1]) * atoi(argv[2]);
cout << argv[1] << " * " << argv[2] << " is: " << total << endl;
} else {
cout << "Enter 2 valid parameters after the program name" << endl;
}
return 0;
}




$ div num num<ENTER>


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

int main(int argc, char* argv[]) {
double total;
if (argc==3) { //only accept three parameters
total = (double) atoi(argv[1]) / (double) atoi(argv[2]);
cout << argv[1] << " / " << argv[2] << " is: " << fixed << setprecision(2) << total << endl;
} else {
cout << "Enter 2 valid parameters after the program name" << endl;
}
return 0;
}

This gets the job done but doesn't really check the parameters to see if they are just integers. I tried to do the checking but that somehow screwed up the negative integers. Anyways, maybe I'll try again over next days.

2 comments:

  1. Try using sscanf() instead of atoi(); check the return value of sscanf to see if the read was successful (valid number).

    ReplyDelete
    Replies
    1. I assume that sscanf()let you check for valid input and assign the parameters into variables in a single statement, but how do you do that?

      here is a failed version:
      if (sscanf(argv, "%*s %d %d", &a, &b)==3)

      Delete