Friday, January 18, 2013
Simple commandline program to add, subtract, multiply, divide two numbers.
#include <iostream>
using namespace std;
int main(int argc, char* argv[ ]) {
int i;
int j;
int result = 0;
bool digit = true;
if (argc != 3) { //Make sure the input are in the right format
cout << "Input formart should be like: add num1 num2" << endl;
}
else { //Check if the arrays contain only digits
for (i = 1; i <= 2 && digit == true; i++) {
for (j = 0; argv[i][j] != 0 && digit == true; j++) {
if (!isdigit(argv[i][j])) {
digit = false;
cout << "The input contain non number" << endl;
}
}
}
}
// Adding two numbers
if (argc == 3 && digit == true) {
for (i = 1; i < argc; i++)
result += atoi(argv[i]);
cout << "The result is: " << result << endl;
}
/*
//Subtracting two numbers
if (argc == 3 && digit == true) {
result = atoi(argv[1]) - atoi(argv[2]);
cout << "The result is: " << result << endl;
}
*/
/*
//Multiplying two numbers
if (argc == 3 && digit == true) {
result = atoi(argv[1]) * atoi(argv[2]);
cout << "The result is: " << result << endl;
}
*/
/*
//Dividing two numbers
if (argc == 3 && digit == true) {
result = atoi(argv[1]) / atoi(argv[2]);
cout << "The result is: " << result << endl;
}
*/
return 0;
}
-------------Seraching for a system environment --------------------
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char* argv[], char* env[]){
int i;
int j;
int targetlen;
char target[30] = {'\0'};
bool found = false;
if (argc > 2)
cout << "You can only print out one system environment each time." << endl;
else {
strcpy(target, argv[1]);
strcat(target, "=");
targetlen = strlen(target);
for(i = 0; env[i] != 0 && found == false; i++){
for (j = 0; j < targetlen; j++){
if (toupper(target[j]) == toupper(env[i][j])) {
found = true;
}
else {
found = false;
j = targetlen;
}
}
}
if (found == true)
cout << env[i-1] << endl;
else
cout << "Not Found" << endl;
}
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment