I/O ------------------- - please read Section 2.2, 2.6.4 of the book. - output - allows multiple values to be printed in one statement using namespace std; cout << a << b << endl; - formatted output #include - To set width of the next output cout << setw(8); // spaces (right justified) output 8 characters cout << setprecision(2); // precision for floating point numbers cout << 3.423 << endl; // prints "....3.42" - setprecision has to be set once - setw has to be set everytime some output is printed - input int a; cin >> a; - suppose you type in 2.3, followed by newline ___________________ | 2 | . | 3 | \n | |____|____|____|____| - a gets 2; - cin stops at . - if you were to read an integer again, nothing would be read - what if you typed a string instead of a number ___________________ | t | e | n | \n | |____|____|____|____| - a would not get any value - cin would be in a "failed" state after the first read - worse, the following could cause an infinite loop while (a < 10) { cin >> a; cout << a << endl; } - what if you typed 2, followed by space, 3 and newline ___________________ | 2 | | 3 | \n | |____|____|____|____| - a would get 2 only after the newline - a subsequent read would get the 3 value - solution to cin failure - test for failure after each input cin >> x; if (!cin.fail()) { // correct input } else { // bad input } - another way while (cin >> x) { // correct input }