#include <QtCore>int StringToInt(char * str, bool & err){ char * pLastChar = NULL; int param = strtol(str, &pLastChar, 10); err = ((*str == '\0') || (*pLastChar != '\0')); return param;}int main(int argc, char * argv[]){ if (argc <= 1) { printf("Program calculates result of elementary mathematical operations with its command line arguments.\n"); return 0; } const char * operation = "+"; double sum = 0; for (int i = 1; i < argc; ++i) { bool err; int param = StringToInt(argv[i], err); if (i % 2 != 0) { if (err == true) { printf("Error in the argument #%d: the numbers should alternate with the operators +, -, *, /.\n", i); return 1; } if (err == false) { if (strcmp(operation, "+") == 0) { sum += (double) param; } if (strcmp(operation, "-") == 0) { sum -= (double) param; } if (strcmp(operation, "*") == 0) { sum *= (double) param; } if (strcmp(operation, "/") == 0) { if (param == 0) { printf("Error in the argument #%d: division by zero.\n", i); } else { sum /= param; } } } } if (i % 2 == 0) { if (err == false) { printf("11Error in the argument #%d: the numbers should alternate with the operators +, -, *, /.\n", i); return 1; } if (err == true) { if ((strcmp(argv[i], "+") == 0) || (strcmp(argv[i], "-") == 0) || (strcmp(argv[i], "*") == 0) || (strcmp(argv[i], "/") == 0)) { operation = argv[i]; } else { printf("22Error in the argument #%d: the numbers should alternate with the operators +, -, *, /.\n", i); return 1; } } } } for (int i = 1; i < argc; ++i) { printf("%s ", argv[i]); } printf("= %.3f", sum); printf("\n"); return 0;}
anton@laptop:~$ '/home/anton/prog/cpp/laba1-2/laba1-2' 2 + 22 + 2 = 4.000anton@laptop:~$ '/home/anton/prog/cpp/laba1-2/laba1-2' 2 - 22 - 2 = 0.000anton@laptop:~$ '/home/anton/prog/cpp/laba1-2/laba1-2' 2 / 22 / 2 = 1.000anton@laptop:~$ '/home/anton/prog/cpp/laba1-2/laba1-2' 2 * 222Error in the argument #2: the numbers should alternate with the operators +, -, *, /.anton@laptop:~$ ^C