-2

So, I've written a C executable on Linux for Windows using mingw32-gcc. It is a basic Input-Output program, you type an input and get an answer. Problem is the cmd shuts down immediately, so the user can't see the output.

Assuming I cannot use Windows to edit the executable there, what should I change in my code/ what flags should I use when compiling it?

inb4:

  • the user is supposed to click and run it, so running it from cmd won't help.
  • adding getchar()/scanf() at the end of my code doesn't work, and it feels a bit like cheating.

SOLVED: so all I had to do was to actually add a getchar() after every scanf() and one more at the end of the code for the user input to close the cmd.

oar
  • 1
  • 2
  • Related: https://stackoverflow.com/q/988403/10553341 – Damien Mar 20 '21 at 11:42
  • No! Your solution (add `getchar()` after every `scanf()`) isn't canonical. The canonical solution is to **exclusively** use `fgets()` for user input. – pmg Mar 20 '21 at 15:01
  • Depending on the type of program it is very unconventional to wait for user input at the end. Why should the programmer care whether the executing shell closes and cleans the screen after use? One could consider it poor behaviour on Windows' part. If you want to see the output, run the command from a CMD or PowerShell window, instead of clicking on the executable. – Cheatah Mar 20 '21 at 20:52
  • @Cheatah I think it really depends on the program use case. If author wants program that will show answer based on user input, then the requirement for command line to stay open make sense. Of course running into this requirement while implementing C program is probably a sign of wrongly chosen language for the purpose, but that's for another discussion. – Risinek Mar 21 '21 at 09:36

1 Answers1

1

Waiting for input at the end is not cheating, but common practice. How else should program know for how long it should stay opened? Closing program by closing console window directly is more cheating than waiting for user input to finish. You can for example prompt user to hit any key like Press any key to exit... or something similar.

If you want some specific delay, you can use Sleep() from windows.h instead of waiting for input. See https://stackoverflow.com/a/3379146/3035795

Risinek
  • 286
  • 1
  • 15