// // Program: print_2cols // // Purpose: print input in two-column format (illustrating // use of array). // // Input: sequence of numbers x1, .. xN (up to 100), from standard // input. // Output: x1, .. xN printed to standard output in two-column // format, with the first half of the numbers forming the first // column. If the user enters more than 100 numbers, the program // prints a warning message and uses only the first 100. // #include #include // has EXIT_SUCCESS // Function prototypes (for comments, see definitions below). bool moreInput(void); // Main program. int main(void) { const int MaxNums = 100; cout << "Enter some integers (no more than " << MaxNums << "), " " control-D to end:\n"; int nums[MaxNums]; int count = 0; // how many numbers were read. // Read numbers until end-of-file on input or array is full. while (count < MaxNums && (cin >> nums[count])) ++count; // Check to see if user has tried to enter more than MaxNums // numbers. if (moreInput()) cout << "Warning: More than " << MaxNums << " numbers entered. Only the first " << MaxNums << " will be used.\n"; // Print numbers back out in desired form: // First print count/2 pairs of elements. For each pair, the // index of the first element is i (starting with i=0), and // the index of the second element is i + (count+1)/2. // Then print out the leftover middle element if count is odd. // (This is a bit tricky. Try some examples with count even, odd // to see how it works.) cout << "You entered:\n"; for (int i = 0; i < count/2; ++i) cout << nums[i] << "\t" << nums[i+(count+1)/2] << endl; if (count%2 == 1) cout << nums[count/2] << endl; return EXIT_SUCCESS; } // Function definitions. // Post: returns true if there is more non-whitespace input to read // on standard input, false if not. bool moreInput(void) { // Already hit end of file in previous attempt to read? if (cin.eof()) return false; // Discard whitespace and check for end of file again. cin >> ws; return !(cin.eof()); }