1

I have a small function which should pause the console, but actually does nothing

void getch()
{
    fflush(stdin);
    getchar();
}

Also, I don't want to use system("pause") or scanf("%c", &temp)

Jason Aller
  • 3,391
  • 28
  • 37
  • 36
HerrNilsen
  • 43
  • 1
  • 8
  • 3
    `fflush(stdin);` invokes *undefined behavior*. Why don't you want to use them? – MikeCAT Sep 28 '20 at 17:34
  • @MikeCAT do you have a reference for that being UB? – AKX Sep 28 '20 at 17:43
  • 2
    `getchar()` alone should be enough, creating a separate function is unnecessary. My guess is that you have other inputs before, and your `getchar()` caches some character that is left in `stdin`. – anastaciu Sep 28 '20 at 17:44
  • `fflush()` is to flush a write buffer, and `stdin` is read-only. If this isn't pausing properly you probably have unread data on `stdin`, so you'll need to read it first. – tadman Sep 28 '20 at 17:44
  • It's relevant to say that MSVC actually defines the behavior of `fflush` with input stream. – anastaciu Sep 28 '20 at 17:47
  • @HerrNilsen, if my guess is correct here is a link where you can find a methods to clear stdin: [How to clear input buffer in C?](https://stackoverflow.com/q/7898215/6865932) – anastaciu Sep 28 '20 at 17:52
  • 3
    @AKX C18: 7.21.5.2 2 If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; **otherwise, the behavior is undefined.** – Weather Vane Sep 28 '20 at 18:21
  • 1
    @anastaciu MSVC defines and says it is a no-op :D – Antti Haapala Sep 28 '20 at 21:14
  • @AnttiHaapala, yes, pesky MSVC, why do they do those things? I feel like it's just to agravate people ;). – anastaciu Sep 29 '20 at 07:43
  • 1
    @anastaciu it changed at some point, the universal CRT says that it is no-op and the older MSVC docs say it discards input buffer. ROTFL. – Antti Haapala Sep 29 '20 at 07:46
  • @AnttiHaapala, what a mess. There a nice answer by Jonathan Leffler around here that goes into some detail. Out of curiosity I tested it and in my case it doesn't do anything. – anastaciu Sep 29 '20 at 07:55
  • @AKX [c - Using fflush(stdin) - Stack Overflow](https://stackoverflow.com/questions/2979209/using-fflushstdin) – MikeCAT Sep 29 '20 at 12:00

0 Answers0