Question: Write a C++ program that will add two or more binary numbers. These binary numbers appear as command-line arguments. The resulting sum is output to
Write a C++ program that will add two or more binary numbers. These binary numbers appear as command-line arguments. The resulting sum is output to standard output (stdout). You may assume only well-formed (valid) binary numbers will be entered as command-line arguments. Design your program as a command. It should take two or more binary numbers following the command on the command line as input and output their binary sum. For example, executing the following command line binadd 101 1100 should result in a value of 10001 being output. Similarly, executing the following binadd 100 1 1101 0 should print 10010 . The format of the binary sum should be a left-justified, left-zero-suppressed binary value; do not produce any output except the binary sum. In the event of an overflow or other error, simply print the letter 'E' as output. REMARKS: Adds two or more binary numbers appearing as command-line // arguments. The resulting sum is sent to stdout. The arguments are // assumed to be well-formed (valid) binary numbers; no error checking // is performed on the arguments. // // For example: binadd 100 1 1101 0 // should print 10010 // // . 1 . 2 . 3 . 4 . 5 . 6 . 7 . //3456789012345678901234567890123456789012345678901234567890123456789012345 #include #include using namespace std; const int MAX_DIGITS = 36; // Maximum digits in (output) sum bool Badd( const char augend[], const char addend[], char sum[] ); // IN IN OUT int main( int argc, char* argv[] ) // IN IN { char partialSum[MAX_DIGITS+1]; // Partial sum of the binary numbers char sum[MAX_DIGITS+1]; // Sum of the binary numbers bool noError; // No error flag // Exit if insufficient arguments were supplied. if (argc < 3) { cout << "Error: insufficient arguments. "; return 1; } // Add together the first two binary numbers on the command-line. noError = Badd( argv[1], argv[2], sum ); // Add any additional binary numbers to the partial sum. for (int counter = 3; noError && counter < argc; counter++) { strcpy( partialSum, sum ); noError = Badd( partialSum, argv[counter], sum ); } // Print answer on standard output. if (noError) cout << sum << endl; else cout << 'E' << endl; return 0; } // end main bool Badd( const char augend[], const char addend[], char sum[] ) // IN IN OUT // Pre: augend and addend are strings representing valid binary numbers. // Post: sum is a string representing the sum of augend + addend. // Returns true if successful in addition, false otherwise. { // Temporary stub code. Return a string representing binary zero. sum[0] = '0'; sum[1] = '\0'; return true; } // end Badd Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
