|
From: Ioannis V. <iv...@at...> - 2003-04-11 11:13:35
|
> -----Original Message-----
> From: dev...@li...
> [mailto:dev...@li...] On Behalf
> Of Andrι Macαrio Barros
> Sent: Friday, April 11, 2003 8:34 AM
> To: Dev-Cpp-Users
> Subject: [Dev-C++] scanf with gets
>
>
> Dear programmers,
>
> I´m having to use the fflush command in the following code:
>
> #include <stdio.h>
> #include <stdlib.h>
>
> int main()
> {
> char name[10];
> int a, b, c;
>
> 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;
> }
>
> The reason is that if I don´t put it, the program doesn´t
> 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.
>
> 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´t use the fflush?
getchar(); or something. You can even do a function in the style:
void clean_stdin()
{
while(getchar()!='\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
* 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
|