delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/11/09/16:15:13

From: Martin Ambuhl <mambuhl AT earthlink DOT net>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: scanf/gets bug?
Date: Mon, 09 Nov 1998 15:13:55 -0500
References: <3645D45E DOT 8A5C98E5 AT usa DOT net>
Organization: Nocturnal Aviation
X-Posted-Path-Was: not-for-mail
X-Accept-Language: en
Mime-Version: 1.0
Lines: 51
NNTP-Posting-Host: 1cust64.tnt9.nyc3.da.uu.net
X-ELN-Date: Mon Nov 9 12:45:38 1998
X-Mailer: Mozilla 4.5 [en] (Win95; I)
Message-ID: <36474D03.22AAF7C@earthlink.net>
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

"Daniël Hörchner" wrote:
> 
> Hello fellow DJGPP-ers,
> I came across a weird problem with DJGPP (GCC 2.8.1). In the following
> program gets() should wait for input, but it doesn't. What's wrong? The
> strange thing is that if I insert a call to getch() between scanf() and
> gets(), getch() waits for input, but gets() still does not. With Turbo
> C++ 3.0 it works fine (i.e., gets() waits for input).

No.  You are relying on undefined behavior.  fflush() is defined only
for output streams, so there nothing that you can assume about the
effect of `fflush(stdin);'  

BTW, You should also never use gets().  Something like this will work
for you:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int x;
    char string[128];
    if (!fgets(string, sizeof string, stdin) ||
         sscanf(string,"%d", &x) != 1) exit(EXIT_FAILURE);
    if (!fgets(string, sizeof string, stdin)) exit(EXIT_FAILURE);
    puts("hello\n");
    return 0;
}


> #include <stdio.h>
> 
> int main(void)
> {
>   int x;
>   char string[10];
> 
>   scanf("%d", &x);
> 
>   fflush(stdin);
>   gets(string);
>   puts("hello");
> 
>   return 0;
> }


-- 
Martin Ambuhl (mambuhl AT earthlink DOT net)
Note: mambuhl AT tiac DOT net will soon be inactive

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019