getline for C-strings

Jun 20, 2011 at 4:01pm
I'm working on a problem in a chapter that's about C-strings, strings, and vectors. It seems the problem wants me to solve it using a C-string or two since it's problem 1 and corresponds with how the chapter starts out on C-strings.

Anyway, I'm trying to understand what's going on when, for example, I'll have something like

1
2
3
4
5
6
7
8
9
10
char s[10];
. . .
cout << "Enter line:" << endl;
cin.getline(s, 10);
. . .
do
{   cout << "Continue? (y or n) ";
    cin >> input;
}
while(input != 'y' && input != 'n');

and if I enter more than the stream size count (e.g., more than 9), the stream doesn't clear and input will be an endless sequence of a character static_cast<int>(input) of "-52." This is what I'll get with Visual C++ 2010, and with Code::Blocks something similar will happen where the stream doesn't seem to clear even if I try to have it cleared manually.

Thanks for any help.
Jun 20, 2011 at 4:07pm
Clearing the stream must work:

1
2
3
4
5
6
7
#include <limits>

...
cout << "Enter line:" << endl;
cin.getline(s, 10);
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
...
Last edited on Jun 20, 2011 at 4:08pm
Jun 20, 2011 at 5:12pm
Thank you, webJose. . . but sadly, I'm not getting that to work either, although I'm sure it should. The outcome is the same. I even tried other valid arguments for cin.ignore. There's really nothing else to the program currently so I don't know why I'd be having such an issue.
Jun 20, 2011 at 5:32pm
I quickly ran a test @ ideone.com and discovered that you must clear the failbit using cin.clear() before cin.ignore().
Jun 20, 2011 at 5:59pm
It works. Thanks also for the tip on ideone.com. Much, much appreciate you!
Jun 20, 2011 at 6:00pm
Yes, ideone.com is heaven! No more will I stuff my hard disk drives with tiny projects to run quick or simple tests or develop certain algorithms.
Topic archived. No new replies allowed.