Thanks guys for your input. I think I sort of got it working. I wanted to purposefully avoid using C++ strings at the moment since I'm learning c-strings now. I took cin.clear() and added cin.ignore(20, '\n') right after that, and it seems to work the way I intended.
cin.clear() seems to 'unclog' whatever was keeping it jammed there. If I had cin.clear without cin.ignore, it would input the first 4 and the next input statement would eat up the remaining characters. Once I added the cin.ignore(#, '\n'), it would properly ask me for name, clear the error, discard what I didn't need, and proceed to ask me for my city.
The description you gave me was helpful in visualizing the process. I did some more reading and found out that the input stream is in a 'fail state' which must be fixed by using cin.clear.
Source:
http://www.velocityreviews.com/forums/t ... oblem.html
When 'cin' encounters a character that is invalid for the
type being extracted, not only does it not read the invalid
character, it goes into a 'fail' state. This is how it
informs you that something went wrong. You check for it
with e.g. if(!cin). The stream remains in this 'fail'
state until explicitly reset. That's what 'clear()' does,
sets the state back to 'good'.
...
A special member function of 'cin' intercepts this attempt
to determine it's 'value' and returns the stream's 'state'
instead. When evaluating 'cin' (or any stream object) in
a boolean context, (as in an if() expression), it produces
a value of 'true' if the stream is in the 'good' state, and
'false' if it is not.
Sorry if this is getting long, but I always like following up my questions if I figure it out with the solution and the sources used so it can be helpful to others if they come across this.
Fixed code:
Code: Select all
#include <iostream>
using namespace std;
int main()
{
char name[20], city[20];
if(cin) cout << "OK!" << endl;
else cerr << "BAD!" << endl; // Not sure if I should be using cerr here..
cout << "Hi, please enter your name: "; // << endl;
cin.getline(name, 5, '\n');
if(cin) cout << "OK!" << endl;
else cerr << "BAD!" << endl; // Not sure if I should be using cerr here..
cin.clear(); // reset stream state to 'good
cin.ignore(20, '\n'); // remove remaining characters in stream for next input
cout << "Please enter your city: "; // << endl;
cin.getline(city, 20, '\n');
cout << endl << endl;
cout << "Your name is: " << name << endl;
cout << "You live in: " << city << endl << endl;
system("Pause");
}
EDIT: I've run into another problem now with the modification. While the above fixed my original problem with names greater than 4 characters, now I have a problem with less than 5... sigh, I'll post if I fix the problem.