2

This is a snippet of my code:

AttachConsole(-1); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); freopen("CONIN$", "r", stdin); //this doesn't seem to do anything int n = 0; cin >> n; cout << n + 1; FreeConsole(); WNDCLASSA MainWindow = { 0 }; MainWindow.hbrBackground = (HBRUSH) COLOR_WINDOW; MainWindow.hCursor = LoadCursor(NULL, IDC_ARROW); MainWindow.hInstance = hInst; //here the window gets created etc. 

Obviously the usage of the console here is basic, but that should do for this question. The problem is that functions like cin or scanf are not working. cout, cerr, clog, printf work fine, but the input functions don't do anything. How can I make stdin work (preferrably with cin)?

19
  • have you tried std::cin.clear() after freopen()ing the streams? Commented Oct 24, 2018 at 18:50
  • Why aren't you using Unicode Commented Oct 24, 2018 at 18:53
  • @J. Doe adding cin.clear() after freopen("CONIN$", "r", stdin) doesn't work. Commented Oct 24, 2018 at 18:56
  • @stackptr I don't need Unicode and I don't see why that is relevant for this question Commented Oct 24, 2018 at 18:57
  • You could try a different method than freopen() described in this article. Commented Oct 24, 2018 at 19:05

1 Answer 1

3

Your /SUBSYSTEM:WINDOWS program will be detached from the console right at its launch and the command processor cmd.exe waits for user input again. So stdin is already in use before your programm can attempt any input operation.

Actually,

#define _CRT_SECURE_NO_WARNINGS #include <windows.h> #include <iostream> int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { AttachConsole(-1); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); freopen("CONIN$", "r", stdin); std::cout.clear(); std::cin.clear(); std::cout << "Hello!\n"; int i; std::cin >> i; std::cout << i << '\n'; std::cin.get(); std::cin.get(); } 

works as expected when run from the command prompt using start /wait foobar.exe. (foobar.exe must be built as x64 to work that way on x64 Windows. Trying with an x86 executable gives funny error messages.)

See How do I write a program that can be run either as a console or a GUI application? for a discussion about the topic.

Sign up to request clarification or add additional context in comments.

15 Comments

it says _O_TEXT is undefined
_O_TEXT is defined in <fcntl.h>
I called this from WinMain and checked if the return value is false. If it is, display a Windows message box, otherwise not. When launched without a console it displays that (obviously), but when launched with a console, it doesn't display that but neither stdin nor stdout are working.
Do you check the return value of your AttachConsole(-1);? Whats the parent process anyway?
yes, I checked it, it only returns TRUE when there actually is a calling console
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.