input stream crashing program

I've been working on my first project in C++, and I have a function where I get a users name. It goes like this:

1
2
3
4
5
6
7
8
9
void getName()
{
     char name[24];
     cout << "Enter your name: ";
     cin.getline(name, 24);
     cin.clear();
     cout << "Your chosen name is ";
     cout << name << endl;
}


It works fine for the most part, but the thing I'm trying to make it do is ignore any input past the first 24 characters. Currently when I run this, if you use say 26 characters, it just crashes.
Please advise! Thanks.
closed account (1yvXoG1T)
Either increase your array size (i.e char name[48];) or do some research on STL strings.
That's one of the many reasons you should not use char arrays.
The correct way to do this is:
1
2
3
string name;
cout << "Enter your name: ";
getline(cin,name);
Ah, good call Athar!

So, how could I limit the amount of characters for the input line then? I'd like to keep the user name short if possible.
You can check the name's length after the input was made and either cut it short or prompt for another name.

if (name.length()>30)doSomething();
Thanks a bunch :)
I should do some more research on string functions like neuro said.
To answer my own question, I came across this:

playerName.resize (10);

seemed to work well.
Make it if (playerName.length()>10)playerName.resize(10); or playerName.resize(min(playerName.length(),10u));, otherwise you'd append null chars to a name shorter than 10 characters.

Edit: unless you already do this. I guess you might.
Last edited on
Topic archived. No new replies allowed.