Key for Homework 3 on I/O Basics in C++ Q A Reason ----------------------------------------------------------------------------------- For questions 1 through 6, we start with the input stream (separated by tabs): 12 4.9 A -46.32 1 3 cin >> anInt // reads the integer 12 into anInt >> aChar; // discards the tab, reads the char '4' into aChar 2 2 See analysis for question 1. 3 3 cin >> aDble // reads the integer 12 and stores the decimal value 12.0 into aDble >> aChar; // discards the tab, reads the char '4' into aChar 4 2 See analysis for question 3. 5 4 cin >> aDble // reads the integer 12 and stores the decimal value 12.0 into aDble >> anInt; // discards the tab, reads the integer 4 into anInt 6 4 See analysis for question 5. 7 3 30 + 12 is evaluated (to 42) before being printed. The setw(3) takes care of the spacing after the word "is". 8 4 The key here is that TestScore holds a 2-digit number and it must be printed right-justified in 4 columns in order to line things up correctly. The first code fragment does that by including 2 spaces in the label string "SCore: " and letting the value of TestScore print in the next 2 spaces. The second code fragment does that by printing 2 spaces as a separate string, after the label, and then printing TestScore. The third string just uses setw(4) to print TestScore. 9 6 We have an input stream containing: 298.173.41.142 For 1: cin >> A; // reads the integer 298 into A cin.ignore(100, '.'); // gets rid of the first period cin >> B; // reads the integer 173 into B For 2: cin >> A; // reads the integer 298 into A char ch; cin.get(ch); // reads the period into ch cin >> B; // reads the integer 173 into B For 3: cin.ignore(100, '.'); // gets rid of everything through the first period cin >> B; // reads the integer 173 into B For 4: cin.get(A); // reads the character '2' into A cin.get(B); // reads the character '9' into B 10 9 According to the specification, we have an input stream of the form: