scanf and c++

X

Xavier Serrand

With GCC version 3.4.4 (mingw special) , following code gives stange results
:


void encapsulation_c(void)
{
double x, y;
std::printf("Calcul de moyenne\n");
std::printf("Entrez le premier nombre : ");
std::scanf("%f", &x);
std::printf("\nEntrez le deuxieme nombre : ");
std::scanf("%f", &y);
//y = 3;
std::printf("\n\nLa valeur moyenne de %8.2f et de %8.2f est %8.2f\n",
x, y, ((x+y)/2));
}

output is :

Calcul de moyenne
Entrez le premier nombre : 1.0

Entrez le deuxieme nombre : 2.0


La valeur moyenne de 0.00 et de 0.00 est 0.00


Some idea ?
 
R

Robert Bauck Hamar

Xavier said:
With GCC version 3.4.4 (mingw special) , following code gives stange
results
:


void encapsulation_c(void)
{
double x, y;
std::printf("Calcul de moyenne\n");
std::printf("Entrez le premier nombre : ");
std::scanf("%f", &x);

std::scanf("%lf", &x);
std::printf("\nEntrez le deuxieme nombre : ");
std::scanf("%f", &y);

std::scanf("%lf", &y);
//y = 3;
std::printf("\n\nLa valeur moyenne de %8.2f et de %8.2f est %8.2f\n",
x, y, ((x+y)/2));
}

output is :

Calcul de moyenne
Entrez le premier nombre : 1.0

Entrez le deuxieme nombre : 2.0


La valeur moyenne de 0.00 et de 0.00 est 0.00


Some idea ?

Read the manual when using printf/scanf. Googling for scanf says exactly
what's needed. Also, the warning

warning: format '%f' expects type 'float*', but argument 2 has
type 'double*'

is also useful.
 
J

James Kanze

With GCC version 3.4.4 (mingw special) , following code gives stange results
:
void encapsulation_c(void)
{
double x, y;
std::printf("Calcul de moyenne\n");
std::printf("Entrez le premier nombre : ");
std::scanf("%f", &x);
std::printf("\nEntrez le deuxieme nombre : ");
std::scanf("%f", &y);
//y = 3;
std::printf("\n\nLa valeur moyenne de %8.2f et de %8.2f est %8.2f\n",
x, y, ((x+y)/2));
}
output is :
Calcul de moyenne
Entrez le premier nombre : 1.0
Entrez le deuxieme nombre : 2.0
La valeur moyenne de 0.00 et de 0.00 est 0.00
Some idea ?

The code has undefined behavior, so nothing can really be
considered strange.

Forget about scanf. It's very difficult to use correctly to
begin with, and very, very fragile, leading to absolutely
unmaintainable code. Something like:

double x, y;
std::cout << "Calcul de moyenne" << std::endl ;
std::cout << "Entrez le premier nombre : " ;
std::cin >> x ;
std::cout << "\nEntrez le deuxieme nombre : " ;
std::cin >> y ;

Does the trick nicely (except that it lacks error handling), and
is robust in face of change. (It works equally well, regardless
of whether x and y are double, float or even int.)
 

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

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top