cin and scanf which is best for simple input

P

papoupapa

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))
ok = 1 ;
else
{
ok = 0 ;
nb_try-- ;
}

if (!ok)
{
cout << "\nEntry outside 0-65535 range\n" ;
cout << nb_try << " left\n\n" ;
}

} while ((!ok) && (nb_try >= 0)) ;

nb_try = 3 ;

do
{
cout << "\nPlease enter 2nd number between 0 and 65,535) : \n" ;
//scanf("%d", &val2) ;
cin >> val2 ;

if (((val1 >= 0) && (val1 < 65536)) && ((val2 >= 0) && (val2 <
65536)))
ok = 1 ;
else
{
ok = 0 ;
nb_try-- ;
}

if (!ok)
{
cout << "\nEntry outside 0-65535 range\n" ;
cout << nb_try << " left\n\n" ;
}

} while ((!ok) && (nb_try >= 0)) ;

cout << "\n\n" ;
system("pause") ;
return 0 ;
}
 
S

Sprechen Sie C++

Might be a better idea to use

#include <iostream>;

std::cout << mydata << std::endl;


easier to work with and 100x more maintainable
 
K

Kai-Uwe Bux

papoupapa said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top