zeroliken
Nearly a Posting Virtuoso
1,346 posts since Nov 2011
Reputation Points: 214
Solved Threads: 205
Skill Endorsements: 13
#1) What zeroliken said
#2) It's C++. Why are you using the terrible and dangerous C function gets() ? Use getline() .
#3) cin is your problem. Reading an int leaves the NEWLINE in the input buffer. The solution has been explained many many times on this site -- do a search.
WaltP
Posting Sage w/ dash of thyme
11,404 posts since May 2006
Reputation Points: 3,421
Solved Threads: 1,055
Skill Endorsements: 36
Wow! I never knew it was a C function. Thanks for sharing that, now onward i will not use that.
The fact that it's a function inherited from C is largely irrelevant. The important piece of information is that gets() is quite literally impossible to use safely. There's always a chance of buffer overflow, and you cannot avoid it. You can create the same problem using cin and C-style strings:
char buf[N];
cin >> buf; // No better than gets()
But at least here there's a fix for it:
char buf[N];
cin >> setw(N) >> buf; // All better
Of course, in C++ you should prefer to use the string class over C-style strings because they're easier to get right.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,483
Solved Threads: 1,407
Skill Endorsements: 53
Question Answered as of 1 Year Ago by
Narue,
WaltP
and
zeroliken