|
From: Ioannis V. <iv...@at...> - 2003-04-11 19:44:01
|
> -----Original Message-----
> From: dev...@li...=20
> [mailto:dev...@li...] On Behalf=20
> Of Andr? Macario Barros
> Sent: Friday, April 11, 2003 8:34 AM
> To: Dev-Cpp-Users
> Subject: [Dev-C++] scanf with gets
>=20
>=20
> Dear programmers,
>=20
> I=B4m having to use the fflush command in the following code:
>=20
> #include <stdio.h>
> #include <stdlib.h>
>=20
> int main()
> {
> char name[10];
> int a, b, c;
>=20
> printf("Enter a-->");
> scanf("%d", &a);
> printf("Enter some name-->");
> fflush(stdin);
The behaviour of the above is undefined (e.g. the airplane may crash).
fflush() is intended to be used on output streams.
You can simply do:
getchar();
> gets(name);
Extremelly Dangerous for buffer overflow (that is you must trust the =
user
very well, and he user must know the internals of your code). A better =
one:
fgets(name,10,stdin);
> printf("Enter com b-->");
> scanf("%d", &b);
> printf("The sum of %d with %d is %d\n", a, b, a+b);
> printf("And the name typed was %s\n", name);
> system("PAUSE");
> return 0;
> }
>=20
> The reason is that if I don=B4t put it, the program doesn=B4t=20
> wait for the name
> to be typed via keyboard. It passes directly to the other operator, b,
> indicating that the input buffer is loaded with something. I made some
> experiments with short int (hd), but nothing solved.
>=20
> 1-Can anyone explain what is happening?
scanf() leaves the '\n' on the stream. Then gets() was reading and
interpreting it as if you entered an empty string.
> 2-What is the solution for don=B4t use the fflush?
getchar(); or something. You can even do a function in the style:
void clean_stdin()
{
while(getchar()!=3D'\n')
;
}
And use it. If you are going to use it with stream redirection in the =
style
myprogram <whatever.txt
for example,
you have to get EOF into account.
Ioannis Vranos
=20
* Programming pages: http://www.noicys.freeurl.com
* Alternative URL 1: http://run.to/noicys
* Alternative URL 2: http://www.noicys.cjb.net
Anti-racism movement: http://www.positive-youthfoundation.org
Iraq Peace Pledge: http://www.peacepledge.org
|