Homework fill in blank question to figure out output

Suppose that you have the following C++ Code segment. Show the contents of each variable and the contents of the Input Buffer after each C++ statement executes.

char ch1, ch2, ch3;
int num;
string data;
Data Entered From the Keyboard: D$121TQ:XM (No Spaces)

C++ Statement Variable Input Buffer Contents
1. cin.get(ch1); ch1 = D IB = $121TQ:XM
2. cin >> ch2; ch2 = IB = D121TQ:XM
3. ch3 = cin.peek(); ch3 = ? IB = ?
4. cin >> num; num = ? IB = ?
5. cin.ignore(3); IB = 21TQ:XM
6. cin.putback(ch2); IB = $121TQ:XM
7. getline(cin,data); data = ? IB = ?

cin.get(ch1) = D, Input Buffer = $121TQ:XD

cin >> ch2; ch2 = $ Input Buffer = D121TQ:XM

ch3 = cin.peek( ); ch3 = (what is variable) InputBuffer = (output)

cin >> num; num = (what is variable) Input Buffer = (what is output)

cin.ignore(3); (no variables) Input Buffer = 21TQ:XM

cin.putback(ch2); (no variables) Input Buffer = $21TQ:XM

getline(cin, data); data = (variable)

Input Buffer = (output)

The ones I have figured out the variable and out of are already answered, the ones I have question marks next to I haven't figured out and need help. Its basically a fill in the blank question.
Surely it would take but 2 minutes to type in the program, add a whole bunch of cout statements for each variable at the end and try it yourself.

Rather than wait hours for someone to do that much for you.
.peek() returns the next available char but doesn't remove it. .get() returns the next available char and does remove it. Ignore removes the next char.

Note that your 2.) answer is incorrect.
4) cin of an int is weird. its going to read the whole thing and consume it all. However if it had started with a valid int and had more junk, eg 123xxx:fubar! it would give you 123 as the int and leave the rest of the buffer intact. It will usually give zero for your case (no valid int, everything consumed) but I am not sure if that is dictated or compiler chosen.

7) is important. getline and cin are at odds, look up online about using both together. The long and short of it is that cin requires you to type enter, which puts a new line in the buffer as well. You need to track IB by that new line here. cin would leave the new line, getline consumes it, so IB is actually for all the cin answers when you think it read all the stuff, it will actually be sitting on the new line (which next cin will ignore as whitespace). getline will read the newline, the buffer is *empty*.
Topic archived. No new replies allowed.