Short answer:
You are misusing cin.ignore()
and cin.clear()
. Remove those two lines.
Long answer:
Let's go step by step through your code.
cin.clear();
First, you ask to clear flags on cin
. There were not flags set, so it doesn't do anything.
cin.ignore( 255, '\n');
You ask to skip next 255 characters or up until '\n' is reached. The stream is empty, so none of these conditions is met until the end of input data. From documentation on std::basic_istream::ignore()
, eof
flag is set on stream and input characters are left in stream.
cin >> fun;
You try to extract data from stream, but eof
flag is set. Extraction fails silently, fun
becomes 0
if you are using C++11 standard or newer, or is left unitialized if you are using old compiler. I'm assuming modern compiler later on.
switch (fun) { }
case 0:
or default:
will be executed.
cin >> choice;
Again, eof
bit set, extraction failed. choice
is zeroed.
} while(choice != 'n');
'\0' != 'n'
, continue the loop.
Now comes the fun part, why it starts working at second loop iteration?
Lets go through the loop again:
cin.clear();
You clear the eof
flag set in previous iteration, stream is non-empty and in good()
state.
cin.ignore( 255, '\n');
You ignore the values inputted in the previous iteration. Depending on how you input values, but it will skip until first \n
.
cin >> fun;
If the next value in the stream is integer, you have successful extraction! From now on, if values inputted are valid for the data type, the loop will work correctly.