/////////////////////////////////////////////////////////////////////////// // Homework:2 // Exercise:1 // // summary: write a simple program to add numbers specified on the command // line, so that if the program is named my_add: // // my_add 34 -23 +434 35 // // would output 480 and then quit // // Steps to implement the program: // // // (1) looping over the command line arguments: // // As you learned in the last homework, argc and argv[] give you access to // the command line arguments. Since we want to add up all the command line // arguments, write the code to loop over all the command line arguments (if any // and print them to the screen. If there are none, output "no arguments provided" // // (2) convert each string to an integer (write a function int atod(char *)). // To add the arguments, you'll have to convert them into an int first. Using // the fact that argv[1], argv[2], ... are all null ('\0')-terminated character // arrays, write a function: // // int atod(char s[]) // // that expects a null-terminated character array that begins with a '+', '-', or // digit (0-9). In this function you'll first loop through the string, accessing // the array using subscripting (i.e. s[3], s[4], etc.) , // looking through for the terminating '\0' that signals the end of the string. // Take, for example, the string to be "123" (4 characters long). After finding // the end of the string loop backward over the string, again using // subscripting, and read in each digit of the number, a character at a time. // If the character is a digit, you can convert it to a number using // the fact that '9'-'0' == 9 // When you run out of digits, check for an explicit + or - sign and flip the sign // of the number as necessary. // // (3) call this function on each of the command line arguments, add up the total // then output the number // // // // // /////////////////////////////////////////////////////////////////////////// #include int main(int argc, char *argv[]) { // # of command line arguments = argc-1, so if argc==1, no args if (argc > 1) cout << "first argument is " << argv[1] <<'\n'; else cout << "no command line arguments"; return 0; }