My program doesn't put characters out on the screen - c++

I have tried several things but none of them did work. Does someone know what the problem is? Here's my code:
#include <iostream>
#include <Windows.h>
#include <iomanip>
#include <fstream>
#include <stdio.h>
using namespace std;
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int CmdShow) {
cout << "Hello World" << endl;
return 0;
}
Thanks

If you are using visual studio, and create a Win32 application, it will not create a console so the output does not appear on any window. If you create a Win32 Console application, std::cout will be directed to the console window but you will need to use a standard main() program entry point.
To avoid creating a new project, modify your code as shown here:
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int CmdShow) {
AllocConsole();
AttachConsole(GetCurrentProcessId());
freopen("CONOUT$", "w", stdout);
cout << "Hello World" << endl;
return 0;
}

On Windows, there are two main types of programs:
Console applications for single textual input and output. These are typically started from the command line in a command prompt.
GUI applications which use windows, buttons, the mouse, touch, etc. These are typically started by choosing from the start menu or double-clicking on an icon.
(There are ways to have a single application work both ways, but that's almost certainly not what you're after.)
Your code is exhibiting indications of trying to be both. It has a wWinMain, which suggests it's a GUI application, but it does regular textual output using std::cout, which suggests it's a console application.
I think you want a console application, but you accidentally started by choosing a Win32 application in the Visual Studio New Project Wizard. To fix this without starting over:
First, get rid of the unnecessary includes, specifically, delete #include <windows.h>.
Next Change the wWinMain to a standard C++ main function, like this:
int main() {
cout << "Hello World" << endl;
return 0;
}
Finally, right-click on your project in the Solution Explorer, and choose Properties from the pop-up menu. At the top of the pop-up dialog, set Configuration to All Configurations. In the left side, expand Linker and choose System, then, on the right side, change the SubSystem field to Console (/SUBSYSTEM:CONSOLE). Click OK.
Now you should be able to rebuild your program and it'll work.
One word of warning: If you run it directly from Visual Studio, a new console window will appear and, in the blink of an eye, your program will complete and the new console window will disappear, which makes it hard to tell if you did the right thing.
If you start your program from a CMD prompt, you won't have that problem. If you want to run from the debugger, put a breakpoint on the return statement in your main function. That will halt the program in the debugger just before it ends, and you'll be able to see what's in the console window. Some people have the program ask for keyboard input right before it finishes, which gives the user a change to see what's in the console window before it vanishes.

It appears you have created a windows application rather than a console application.
A console application has a main function with signature:
int main(int argc, char ** argv);
A windows application has a main function with signature:
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int CmdShow);
The latter is intended for applications that actually create a window. You choose which to create using the wizard in Visual Studio when you go to create a new project (assuming you are using Visual Studio).
Use:
https://msdn.microsoft.com/en-us/library/ms235629.aspx
Also, it is possible your application is exiting before you see the output.
In this case, we can use a non-standard platform specific call to ::system("pause") to make it wait until you hit a key to continue.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <windows.h>
using namespace std;
int main(int argc, char ** argv)
{
cout << "Hello World" << endl;
system("pause");
return 0;
}
Alternativly, place a break point on the line where it says return 0; and use F5 to debug.

Related

How to conditionally enable console without opening separate console window

I'd like to create a windows application that, under normal conditions, does not have any connected terminal, but may have one in some conditions. I tried two different routes. Option A, creating a normal console application, and conditionally calling FreeConsole():
int main()
{
if (someCondition) {
HANDLE stdOutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
WriteConsoleA(stdOutHandle, "hello world\n", 12, NULL, NULL);
} else {
FreeConsole();
// normal operation
}
return 0;
}
And option B, creating a WinMain based application, and conditionally calling AllocConsole().
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nCmdShow)
{
if (someCondition) {
AllocConsole();
HANDLE stdOutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
WriteConsoleA(stdOutHandle, "hello world\n", 12, NULL, NULL);
}
else {
// normal operation
}
return 0;
}
The problem with option A, is that it doesn't act exactly like a windows application, in that you can very briefly see a console window open up before normal operation continues. This isn't a huge problem, but I'd prefer the program to act, as I said, exactly like a normal windows application.
The problem with option B is that, if the program is invoked from an existing terminal, it opens up a separate terminal window and outputs to that, instead of outputting to the terminal from which it was invoked. This is a much bigger problem.
What is the appropriate solution to conditionally behave as either a console program or a windows program, without either of the problems described above?
Edit
Based on a suggestion in the comments, I tried to use the AttachConsole function.
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nCmdShow)
{
if (someCondition) {
AttachConsole(ATTACH_PARENT_PROCESS);
HANDLE stdOutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
Sleep(3000);
WriteConsoleA(stdOutHandle, "hello world\n", 12, NULL, NULL);
FreeConsole();
}
else {
// normal operation
}
return 0;
}
This seems to be on the right track, but there is still something missing, because my shell prompt is immediately printed out without waiting for the program to finish.
Impossible.
AttachConsole does not work 100% because cmd.exe actually checks if the process it is about to start is a GUI app or not, and alters its behavior.
The only way to make it work is to have two programs; myapp.com and myapp.exe. %PathExt% lists .com before .exe so you can make a console .exe and rename it .com at it will be executed if the user runs "myapp" (but will not work if the user types "myapp.exe"). If your program is not very big you can just ship two versions. If the program is large you can move most of the code to a .dll or make the .com a small helper that calls the .exe with a command line parameter and some pipes for stdin/stdout. Visual Studio does this (devenv.com).
If you want to check if there is already a console, check for a NULL return from GetConsoleWindow(). If it returns null, then do the AllocConsole procedure and other setup (SetWindowLong, SetConsoleMode etc)
int main() programs don't make a console by default, they happen to attach into a console if run through cmd/ps.
One way is the following:
BOOL WINAPI
AttachOrCreateConsole()
{
if(AttachConsole(ATTACH_PARENT_PROCESS))
{
return TRUE;
}
return AllocConsole();
}
This will use the parent console if available and fall back to creating one if needed.
Note that if yo do this and want to use the standard C/C++ I/O mechanisms (stdin/std::cin, stdout/std::cout) you will need to do the work needed to associate those streams to the console handle. There is plenty of material available on how to do that.

VS C++ application leaving background process open

I've got a VS c++ project using SFML that I'm working on but every time i close the program it leaves a background process open after the project has been exited.image of task manager here
I know roughly why this is happening but haven't found any other articles online with this issue. This issue started popping up after i started closing the console window upon startup of my program. In an attempt to remedy this (since i no longer need the console window anyways) I've tried to convert the project to a windows application, but the problem is persisting, I'll include the code in my main, any help is appreciated.
#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <SFML/Graphics.hpp>
#include "gameStates/StateStack.h"
using namespace std;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
bool close = false;
StateStack game;
do
{
game.handleEvents();
game.update();
game.draw();
}while(!close);
return 0;
}

On release mode cout does not print anything

I have a very weird problem. I am working with visual studio in C++ and suddenly cout does not work on release mode (It worked until now) and on debug mode it works fine. I have no idea why thats happans. I have tried to delete some code And I deleted almost all my program (I have backup). Here is my code:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow )
{
AllocConsole();
cout<<"asdasd"<<endl;
cin.get();
return 1;
}
In debug mode the program wait for the user for pressing Enter. In release mode it doesn't. The window just close.
I think that it might be a problem in the setting of visual. Can it be?
iostreams require initialization that's normally carried out by the startup code for a console application -- but since you're using WinMain instead of main as your entry point, it's being linked as a Windows-mode application instead of a console-mode application, so that initialization isn't happening (dependably, anyway). Under some (poorly defined) circumstances, things work anyway, but it's undependable at best.
Unless you're feeling so masochistic that you're willing to do a lot of extra work just to make your code non-portable, write your code the standard way:
#include <iostream>
int main() {
std::cout<<"asdasd\n";
std::cin.get();
return 1;
}
Short, simple, and dependable are all good things. Portable is kind of nice too.

How do I print to the debug output window in a Win32 app?

I've got a win32 project that I've loaded into Visual Studio 2005. I'd like to be able to print things to the Visual Studio output window, but I can't for the life of me work out how. I've tried 'printf' and 'cout <<' but my messages stay stubbornly unprinted.
Is there some sort of special way to print to the Visual Studio output window?
You can use OutputDebugString. OutputDebugString is a macro that depending on your build options either maps to OutputDebugStringA(char const*) or OutputDebugStringW(wchar_t const*). In the later case you will have to supply a wide character string to the function. To create a wide character literal you can use the L prefix:
OutputDebugStringW(L"My output string.");
Normally you will use the macro version together with the _T macro like this:
OutputDebugString(_T("My output string."));
If you project is configured to build for UNICODE it will expand into:
OutputDebugStringW(L"My output string.");
If you are not building for UNICODE it will expand into:
OutputDebugStringA("My output string.");
If the project is a GUI project, no console will appear. In order to change the project into a console one you need to go to the project properties panel and set:
In "linker->System->SubSystem" the value "Console (/SUBSYSTEM:CONSOLE)"
In "C/C++->Preprocessor->Preprocessor Definitions" add the "_CONSOLE" define
This solution works only if you had the classic "int main()" entry point.
But if you are like in my case (an openGL project), you don't need to edit the properties, as this works better:
AllocConsole();
freopen("CONIN$", "r",stdin);
freopen("CONOUT$", "w",stdout);
freopen("CONOUT$", "w",stderr);
printf and cout will work as usual.
If you call AllocConsole before the creation of a window, the console will appear behind the window, if you call it after, it will appear ahead.
Update
freopen is deprecated and may be unsafe. Use freopen_s instead:
FILE* fp;
AllocConsole();
freopen_s(&fp, "CONIN$", "r", stdin);
freopen_s(&fp, "CONOUT$", "w", stdout);
freopen_s(&fp, "CONOUT$", "w", stderr);
To print to the real console, you need to make it visible by using the linker flag /SUBSYSTEM:CONSOLE. The extra console window is annoying, but for debugging purposes it's very valuable.
OutputDebugString prints to the debugger output when running inside the debugger.
If you want to print decimal variables:
wchar_t text_buffer[20] = { 0 }; //temporary buffer
swprintf(text_buffer, _countof(text_buffer), L"%d", your.variable); // convert
OutputDebugString(text_buffer); // print
Consider using the VC++ runtime Macros for Reporting _RPTN() and _RPTFN()
You can use the _RPTn, and _RPTFn macros, defined in CRTDBG.H, to
replace the use of printf statements for debugging. These macros
automatically disappear in your release build when _DEBUG is not
defined, so there is no need to enclose them in #ifdefs.
Example...
if (someVar > MAX_SOMEVAR) {
_RPTF2(_CRT_WARN, "In NameOfThisFunc( ),"
" someVar= %d, otherVar= %d\n", someVar, otherVar );
}
Or you can use the VC++ runtime functions _CrtDbgReport, _CrtDbgReportW directly.
_CrtDbgReport and _CrtDbgReportW can send the debug report to three different destinations: a debug report file, a debug monitor (the
Visual Studio debugger), or a debug message window.
_CrtDbgReport and _CrtDbgReportW create the user message for the debug report by substituting the argument[n] arguments into the format
string, using the same rules defined by the printf or wprintf
functions. These functions then generate the debug report and
determine the destination or destinations, based on the current report
modes and file defined for reportType. When the report is sent to a
debug message window, the filename, lineNumber, and moduleName are
included in the information displayed in the window.
If you need to see the output of an existing program that extensively used printf w/o changing the code (or with minimal changes) you can redefine printf as follows and add it to the common header (stdafx.h).
int print_log(const char* format, ...)
{
static char s_printf_buf[1024];
va_list args;
va_start(args, format);
_vsnprintf(s_printf_buf, sizeof(s_printf_buf), format, args);
va_end(args);
OutputDebugStringA(s_printf_buf);
return 0;
}
#define printf(format, ...) \
print_log(format, __VA_ARGS__)
Your Win32 project is likely a GUI project, not a console project. This causes a difference in the executable header. As a result, your GUI project will be responsible for opening its own window. That may be a console window, though. Call AllocConsole() to create it, and use the Win32 console functions to write to it.
I was looking for a way to do this myself and figured out a simple solution.
I'm assuming that you started a default Win32 Project (Windows application) in Visual Studio, which provides a "WinMain" function. By default, Visual Studio sets the entry point to "SUBSYSTEM:WINDOWS". You need to first change this by going to:
Project -> Properties -> Linker -> System -> Subsystem
And select "Console (/SUBSYSTEM:CONSOLE)" from the drop-down list.
Now, the program will not run, since a "main" function is needed instead of the "WinMain" function.
So now you can add a "main" function like you normally would in C++. After this, to start the GUI program, you can call the "WinMain" function from inside the "main" function.
The starting part of your program should now look something like this:
#include <iostream>
using namespace std;
// Main function for the console
int main(){
// Calling the wWinMain function to start the GUI program
// Parameters:
// GetModuleHandle(NULL) - To get a handle to the current instance
// NULL - Previous instance is not needed
// NULL - Command line parameters are not needed
// 1 - To show the window normally
wWinMain(GetModuleHandle(NULL), NULL,NULL, 1);
system("pause");
return 0;
}
// Function for entry into GUI program
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
// This will display "Hello World" in the console as soon as the GUI begins.
cout << "Hello World" << endl;
.
.
.
Result of my implementation
Now you can use functions to output to the console in any part of your GUI program for debugging or other purposes.
You can also use WriteConsole method to print on console.
AllocConsole();
LPSTR lpBuff = "Hello Win32 API";
DWORD dwSize = 0;
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), lpBuff, lstrlen(lpBuff), &dwSize, NULL);
This works for C++ under MSVC, and even for GUI applications when being run via Debugger. It also gets omitted entirely from release builds. It even uses a C++ stringstream for flexible input.
#include <iostream>
#ifdef _MSC_VER
#include "Windows.h"
#endif
#if !defined(NDEBUG) && defined(_MSC_VER)
#define LOG(args) {std::stringstream _ss; _ss << __FILE__ << "#" << __LINE__ << ": " \
<< args << std::endl; OutputDebugString(_ss.str().c_str());}
#else
#define LOG(args)
#endif
Use like:
LOG("some message " << someValue);

Create an Application without a Window

How would you program a C/C++ application that could run without opening a window or console?
When you write a WinMain program, you automatically get the /SUBSYSTEM option to be windows in the compiler. (Assuming you use Visual Studio). For any other compiler a similar option might be present but the flag name might be different.
This causes the compiler to create an entry in the executable file format (PE format) that marks the executable as a windows executable.
Once this information is present in the executable, the system loader that starts the program will treat your binary as a windows executable and not a console program and therefore it does not cause console windows to automatically open when it runs.
But a windows program need not create any windows if it need not want to, much like all those programs and services that you see running in the taskbar, but do not see any corresponding windows for them. This can also happen if you create a window but opt not to show it.
All you need to do, to achieve all this is,
#include <Windows.h>
int WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int cmdShow)
{
/* do your stuff here. If you return from this function the program ends */
}
The reason you require a WinMain itself is that once you mark the subsystem as Windows, the linker assumes that your entry point function (which is called after the program loads and the C Run TIme library initializes) will be WinMain and not main. If you do not provide a WinMain in such a program you will get an un-resolved symbol error during the linking process.
In windows:
#include <windows.h>
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
// <-- Program logic here
return 0;
}
Be sure to use the /SUBSYSTEM linker switch as mentioned by Adam Mitz.
On other platforms:
int main(int argc, char**argv)
{
// <-- Program logic here
return 0;
}
If you have a need to contiguously run your program without having console or window you might find useful deamon on *NIX or services on Windows, this .NET example if you need plain win32 just google a little bit for sample.
Since your question tagged as win32 i assume that services are more relevant for you.
This also processes messages:
#include <windows.h>
#include <stdio.h>
int CALLBACK WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
MSG msg;
DWORD curThreadId;
curThreadId = GetCurrentThreadId();
// Send messages to self:
PostThreadMessage(curThreadId, WM_USER, 1, 2);
PostThreadMessage(curThreadId, WM_USER+1, 3, 4);
PostThreadMessage(curThreadId, WM_USER+2, 5, 6);
PostThreadMessage(curThreadId, WM_USER+3, 7, 8);
PostThreadMessage(curThreadId, WM_QUIT, 9, 10);
while (GetMessage(&msg, NULL, 0, 0)) {
printf("message: %d; wParam: %d; lParam: %d\n", msg.message, msg.wParam, msg.lParam);
}
return (int) msg.wParam;
}
In Visual Studio Express 2010 after setting the subsystem to windows (as suggested by user17224), alternatively to changing the main to WinMain (as suggested by user17224 and Brian R. Bondy), one can set the entry function to main in properties, linker, advanced, entry point: just type main in the text box.
Use Visual Studio wizard to create the Win32 Application. But don't create the window i.e., you remove the window creation function.
Alternatively we can create Win Service application.
If you are using MSVC or Visual Studio just use the new Project Wizard and select the Console Application.