Wednesday 16 January 2013


Add with checking for valid input


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

using namespace std;


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

int sum;
int i;
int j;
int check = 0;
if (argc == 3) { // can only handle 3 parameters
for (j=1; j<=2 && check==0; j++) {
if (!isdigit(argv[j][0]) && argv[j][0]!='-')
// special check for the first char, which may be '-'
check=1;
for (i=1; argv[j][i]!='\0' && check==0; i++) {
if (!isdigit(argv[j][i]))
check=1;
}
}
}
if (argc==3 && check==0) {
sum = atoi(argv[1]) + atoi(argv[2]);
cout << sum << endl;
} else {
cout << "Enter 2 valid parameters after the program name" << endl;
}
return 0;
}

I don't think I'll post the the other three math programs with validation, it's the same code as the blue section.


No comments:

Post a Comment