CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    May 2002
    Posts
    63

    clear the istream-buffer

    If I want to read to a buffer a specified number of characters I'll use:
    Code:
    char text[12];
    ...
    cin >> setw(sizeof(text) / sizeof(char)) >> text;
    But if the user writes more than 11 characters I'm in trouble when I want to read next time:
    Code:
    int i = 0;
    ...
    cin >> i;
    I'm gessing that the characters the user put in that the first cin ignored still is in the istream-buffer, but I don't know how to clear the istream-buffer.

    I tryed to use also:
    Code:
    cin.getline(text, 12);
    but it works only worse.

    Any suggestions?
    Suzi

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725
    maybe something like this ??

    Code:
          cin >> setw(sizeof(text) / sizeof(char)) >> text;
          cin.ignore(80,'\n');  // ignore rest of line

  3. #3
    Join Date
    May 2002
    Posts
    63
    Yes, it works, thanks.

    But if the user writes more than 80+12 characters it's still the same problem, right?
    This should work I think, but is there a better way?

    Code:
    cin >> setw(sizeof(text) / sizeof(char)) >> text;
    cin.ignore(80,'\n');
    while(cin.gcount() == 80)
        cin.ignore(80,'\n');

    /Suzi

  4. #4
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725
    The way Josuttis does it in his book is to put
    the maximum value for int as the first parameter
    of the ignore() function :

    Code:
    #include <limits>
    //
    //
    //
    cin.ignore(numeric_limits<int>::max(),'\n');

  5. #5
    Join Date
    Jul 2002
    Location
    American Continent
    Posts
    340
    The ignore() member function is intrinsically frauded and should never be used.

    What do you end up ignoring, when you call ignore()? The stuff you ignored must be either valid data or invalid data, right?

    If you ignored VALID data, you are doing a bad thing, you are throwing away legitimate data that you should read in.

    If you ignored INVALID data, you are doing a bad thing, too. The input contains invalid data that shouldn't be there at first place, so this is an error condition that you should deal with properly, instead of just ignoring them.

    Like the "123a" case the other poster raised. the "a" doesn't belong there, it is invalid data. You can't just ignore it, you should report it as an error.

    The only correct use of ignore() is when it ignored nothing. But then you are wasting your time doing nothing useful. So it is still a bad usage of ignore().

    If you have to use ignore(), something is fundamentally wrong.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured