Re: std::cin.ignore() and std::cin.clear()
From: tom_usenet (tom_usenet_at_hotmail.com)
Date: 01/06/04
- Next message: P.J. Plauger: "Re: [OT?] C++ Standard - 14882:2003"
- Previous message: Lew Pitcher: "Re: endianness and sscanf/sprintf"
- In reply to: Chris Mantoulidis: "std::cin.ignore() and std::cin.clear()"
- Next in thread: Kevin Saff: "Re: std::cin.ignore() and std::cin.clear()"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 06 Jan 2004 13:24:24 +0000
On 6 Jan 2004 04:25:43 -0800, cmad_x@yahoo.com (Chris Mantoulidis)
wrote:
>Let's say I have this:
>
>std::string s1;
>std::cin >> s1;
>
>This will read s1 from cin until it finds a space (or a newline,
>whichever comes first).
>
>Okay this works. But when I want to continue reading it reads what's
>left over in the cin, and well that's logical.
>
>At first I thought that std::cin.clear() would sort that out, but it
>didn't... So what does clear() do anyway, if not clear all cin data?
It clears the error state of the stream. If it's at eof(), or the last
operation failed (and set fail()), then you can call clear() to set
the state back to good() so that you can continue using the stream
(all operations fail when a stream isn't good()).
>
>I looked it some places and saw that ignore is what I needed...
>
>std::ignore(1000, '\n'); (or something bigger than 1000 characters).
>
>However I don't like this very much... What if there were 10^100 other
>characters in the input before the new line (this isn't possible I
>guess but I'm just trying to explain why I don't like that way).
I can see why you don't like that, but the correct code (by the new
2003 update to the standard) is
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
The extracts an unlimited amount of characters (the max is a sentinel
value). A bit verbose, but you can always write a little inline
function.
Tom
C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
- Next message: P.J. Plauger: "Re: [OT?] C++ Standard - 14882:2003"
- Previous message: Lew Pitcher: "Re: endianness and sscanf/sprintf"
- In reply to: Chris Mantoulidis: "std::cin.ignore() and std::cin.clear()"
- Next in thread: Kevin Saff: "Re: std::cin.ignore() and std::cin.clear()"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|