cin.getline() problems
Posted: Fri Feb 13, 2009 2:05 am
I'm having a problem with cin.getline(). I'm creating a char array of 20, but only want to store 4 of the characters for the name input. If the name is 4 characters or less, it works fine. If I input a name that is 5 or more characters, it will skip the next input, in this case cin.getline(city, 20, '\n'). It doesn't even store the extra characters that got cut off from the previous getline (as far as I'm aware), it outputs blanks . The compiler I'm using is DEV-C++. And yes, I did search online for suggestions, but I haven't found any clear answers yet. If anyone can take a quick look at the code below and see whats going on, I'll deeply appreciate you helping a noob. Thanks.
Code: Select all
#include <iostream>
using namespace std;
int main()
{
char name[20],
city[20];
cout << "Hi, please enter your name: ";
cin.getline(name, 5, '\n');
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");
}