Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c++ > #6626
| From | Kai-Uwe Bux <jkherciueh@gmx.net> |
|---|---|
| Newsgroups | comp.lang.c++ |
| Subject | Re: cin and scanf which is best for simple input |
| Followup-To | comp.lang.c++ |
| Date | 2011-06-11 20:29 +0200 |
| Organization | University of Bielefeld |
| Message-ID | <it0c5i$nm3$1@hoshi.visyn.net> (permalink) |
| References | <a0468c57-e5e2-4076-a27b-008a19b533d8@g28g2000yqa.googlegroups.com> |
Followups directed to: comp.lang.c++
papoupapa wrote:
> Hi,
>
> Can someone tell from the code below why scanf solves the issue of a
> number out of
>
> the range and cin seems to read twice a great number such as
> 100000000000 or go into a wild loop if a character or some text is
> entered.
>
> #include "std_lib_facilities.h"
>
> int main()
> {
> int val1 = 0 ;
> int val2 = 0 ;
> int nb_try ;
> bool ok = 0 ;
>
> cout << "\nThis code reads 2 numbers and takes these 2 numbers into
> simple
>
> processes : \n" ;
>
> nb_try = 3 ;
> do
> {
> cout << "\nPlease enter 1st number (between 0 and 65,535) : \n" ;
> //scanf("%d", &val1) ;
> cin >> val1 ;
>
> if ((val1 >= 0) && (val1 < 65536))
You test whether val1 is in the required range. However, you have no test
for whether the reading from cin succeeded. You could try:
if ( ( cin >> val1 ) && ( val1 >= 0 ) && ( val1 < 65536 ) ) {
...
}
[snip]
Best,
Kai-Uwe Bux
Back to comp.lang.c++ | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
cin and scanf which is best for simple input papoupapa <papoupapoug@gmail.com> - 2011-06-11 03:53 -0700
Re: cin and scanf which is best for simple input "osmium" <r124c4u102@comcast.net> - 2011-06-11 12:06 -0500
Re: cin and scanf which is best for simple input "Sprechen Sie C++" <spamabuse@hotmail.com> - 2011-06-11 10:50 -0700
Re: cin and scanf which is best for simple input Kai-Uwe Bux <jkherciueh@gmx.net> - 2011-06-11 20:29 +0200
Re: cin and scanf which is best for simple input papoupapa <papoupapoug@gmail.com> - 2011-06-12 16:25 -0700
csiph-web