Displaying Output on the Console Issue - c++

I am working in a MFC application which runs in both GUI mode and user can run from command prompt. In GUI mode I work fine. But in command prompt mode, I used printf() to display the error, but nothing comes in the command prompt. To solve this I got the function AttachConsole(ATTACH_PARENT_PROCESS) to display the content to the console. But the output is not sterilized i.e. if I run the application in the command line the out put will look like bellow
G:\Bin\conTest\Debug>conTest.exe
G:\Bin\conTest\Debug>This is test comment
Press any key to continue . . .
But I want the output to be like bellow
G:\Bin\conTest\Debug>conTest.exe
This is test comment
Press any key to continue . . .
G:\Bin\conTest\Debug>
Please help me to solve the problem,
Bellow is the code snippet
DWORD written;
if (AttachConsole(ATTACH_PARENT_PROCESS))
{
out = GetStdHandle (STD_OUTPUT_HANDLE);
}
CString dump = "This is test comment\n";
WriteConsole (out, (LPCTSTR) dump, dump.GetLength(), &written, 0);
system("pause");
FreeConsole();

Maybe this fix your issue:
Go to Project>Project Properties>Linker>System and in the right pane, set SubSystems option to Console(/SUBSYSTEM:CONSOLE)

Use this string instead:
CString dump = "\n\nThis is test comment\n";

Related

Trying to display a text through CMD with C++ and I am presented with a error [duplicate]

This is a probably an embarasing question as no doubt the answer is blindingly obvious.
I've used Visual Studio for years, but this is the first time I've done any 'Console Application' development.
When I run my application the console window pops up, the program output appears and then the window closes as the application exits.
Is there a way to either keep it open until I have checked the output, or view the results after the window has closed?
If you run without debugging (Ctrl+F5) then by default it prompts your to press return to close the window. If you want to use the debugger, you should put a breakpoint on the last line.
Right click on your project
Properties > Configuration Properties > Linker > System
Select Console (/SUBSYSTEM:CONSOLE) in SubSystem option or you can just type Console in the text field!
Now try it...it should work
Starting from Visual Studio 2017 (15.9.4) there is an option:
Tools->Options->Debugging->Automatically close the console
The corresponding fragment from the Visual Studio documentation:
Automatically close the console when debugging stops:
Tells Visual Studio to close the console at the end of a debugging session.
Here is a way for C/C++:
#include <stdlib.h>
#ifdef _WIN32
#define WINPAUSE system("pause")
#endif
Put this at the top of your program, and IF it is on a Windows system (#ifdef _WIN32), then it will create a macro called WINPAUSE. Whenever you want your program to pause, call WINPAUSE; and it will pause the program, using the DOS command. For other systems like Unix/Linux, the console should not quit on program exit anyway.
Goto Debug Menu->Press StartWithoutDebugging
If you're using .NET, put Console.ReadLine() before the end of the program.
It will wait for <ENTER>.
try to call getchar() right before main() returns.
(/SUBSYSTEM:CONSOLE) did not worked for my vs2013 (I already had it).
"run without debugging" is not an options, since I do not want to switch between debugging and seeing output.
I ended with
int main() {
...
#if _DEBUG
LOG_INFO("end, press key to close");
getchar();
#endif // _DEBUG
return 0;
}
Solution used in qtcreator pre 2.6. Now while qt is growing, vs is going other way. As I remember, in vs2008 we did not need such tricks.
just put as your last line of code:
system("pause");
Here's a solution that (1) doesn't require any code changes or breakpoints, and (2) pauses after program termination so that you can see everything that was printed. It will pause after either F5 or Ctrl+F5. The major downside is that on VS2013 Express (as tested), it doesn't load symbols, so debugging is very restricted.
Create a batch file. I called mine runthenpause.bat, with the following contents:
%1 %2 %3 %4 %5 %6 %7 %8 %9
pause
The first line will run whatever command you provide and up to eight arguments. The second line will... pause.
Open the project properties | Configuration properties | Debugging.
Change "Command Arguments" to $(TargetPath) (or whatever is in "Command").
Change "Command" to the full path to runthenpause.bat.
Hit OK.
Now, when you run, runthenpause.bat will launch your application, and after your application has terminated, will pause for you to see the console output.
I will post an update if I figure out how to get the symbols loaded. I tried /Z7 per this but without success.
add “| pause” in command arguments box under debugging section at project properties.
You could run your executable from a command prompt. This way you could see all the output. Or, you could do something like this:
int a = 0;
scanf("%d",&a);
return YOUR_MAIN_CODE;
and this way the window would not close until you enter data for the a variable.
Just press CNTRL + F5 to open it in an external command line window (Visual Studio does not have control over it).
If this doesn't work then add the following to the end of your code:
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
This wait for you to press a key to close the terminal window once the code has reached the end.
If you want to do this in multiple places, put the above code in a method (e.g. private void Pause()) and call Pause() whenever a program reaches a possible end.
A somewhat better solution:
atexit([] { system("PAUSE"); });
at the beginning of your program.
Pros:
can use std::exit()
can have multiple returns from main
you can run your program under the debugger
IDE independent (+ OS independent if you use the cin.sync(); cin.ignore(); trick instead of system("pause");)
Cons:
have to modify code
won't pause on std::terminate()
will still happen in your program outside of the IDE/debugger session; you can prevent this under Windows using:
extern "C" int __stdcall IsDebuggerPresent(void);
int main(int argc, char** argv) {
if (IsDebuggerPresent())
atexit([] {system("PAUSE"); });
...
}
Either use:
cin.get();
or
system("pause");
Make sure to make either of them at the end of main() function and before the return statement.
You can also use this option
#include <conio.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
.
.
.
getch();
return 0;
}
In my case, i experienced this when i created an Empty C++ project on VS 2017 community edition. You will need to set the Subsystem to "Console (/SUBSYSTEM:CONSOLE)" under Configuration Properties.
Go to "View" then select "Property Manager"
Right click on the project/solution and select "Property". This opens a Test property page
Navigate to the linker then select "System"
Click on "SubSystem" and a drop down appears
Choose "Console (/SUBSYSTEM:CONSOLE)"
Apply and save
The next time you run your code with "CTRL +F5", you should see the output.
Sometimes a simple hack that doesnt alter your setup or code can be:
Set a breakpoint with F9, then execute Debug with F5.
Since running it from VS attaches the VS debugger, you can check for an attached debugger:
if (Debugger.IsAttached)
{
Console.WriteLine("Debugger is attached. Press any key to exit.");
Console.ReadKey();
}
I guess the only caveat is that it'll still pause if you attach any other debugger, but that may even be a wanted behavior.
Use Console.ReadLine() at the end of the program. This will keep the window open until you press the Enter key. See https://learn.microsoft.com/en-us/dotnet/api/system.console.readline for details.
Visual Studio 2015, with imports. Because I hate
when code examples don't give the needed imports.
#include <iostream>;
int main()
{
getchar();
return 0;
}
Currently there is no way to do this with apps running in WSL2. However there are two work-arounds:
The debug window retains the contents of the WSL shell window that closed.
The window remains open if your application returns a non-zero return code, so you could return non-zero in debug builds for example.
It should be added that things have changed since then. On Windows 11 (probably 10, I can't check any more) the new Terminal app that now houses the various console, PowerShell and other sessions has its own settings regarding closing. Look for it in Settings > Defaults > Advanced > Profile termination behavior.
If it's set to close when a program exits with zero, then it will close, even if VS is told otherwise.
Go to Setting>Debug>Un-check close on end.

Executing a command shell from popen and set other command shell

I'm working in a project with a quadrotor and mavlink. I have successfully installed mavproxy in my Ubuntu PC and and ran it without problems from terminal. When I run mavproxy.py from the terminal and connected a quadrotor with support for mavlink (APM autopilot), mavproxy detects the quadrotor and everything is ok.
When you execute mavproxy.py the program in the terminal begin to send and receive several parameters. You can write in the terminal some parameter to access for any configuration. For example, the command help in the terminal:
$ mavlink.py
.
.data beging
.
STABILIZE> "when the program finish the configuration, allowed to you for doing an input any parameter, for example help"
STABILIZE>help
show all helps.
I have a code to execute mavlink.py from C++
include <iostream>
include <stdio.h>
using namespace std;
int main() {
FILE *in;
char buff[512];
if(!(in = popen("mavlink.py", "r"))){
return 1;
}
while(fgets(buff, sizeof(buff), in)!=NULL){
cout << buff;
}
pclose(in);
return 0;
}
When I run this C++ program the terminal shows the same things that would appear if I were running mavproxy.py from the terminal, but I don´t know how can I send a command such as help in the C++ code.
If you read the program, the while statement allows me to capture the parameters generated from the program mavproxy.py and cout in the terminal, but mavlink.py never ends until you write something in the terminal exit or press CTRL + C so the while loop never ends.
I have been reading about the Popen function, but I haven't found the correct form to do this.
I know that I can use the mavlink.h library in my program and send parameters to the quadrotor, but don't want do this with mavlink.h.
I am not sure I understand your question, but I think you want to send commands to mavlink.py as well as read its output.
If that is the case, you must change the open mode of popen() from "r" to "w" so you can write, then you can send commands to it like this:
FILE *fp;
char *command="HELP";
if(!(fp = popen("mavlink.py", "w"))){
return 1;
fwrite(command, sizeof(char), strlen(command), fp);

Run command line process as admin Qt

I am writing a Qt application that needs to call system programs (netsh) and run them as administrator.
However, QProcess, QDesktopServices and system() don't allow me to run the application as administrator (not even with runas).
The only solution that I found is to use ShellExecute, but it does not even open the program.
My code is:
#ifdef Q_OS_WIN {
ShellExecute(0, LPCWSTR("runas"), LPCWSTR("netsh wlan start hostednetwork"), 0, 0, SW_SHOWNORMAL);
}
I have also tried to use other options, such as open and tried to run other programs, such as Notepad (notepad.exe) and Control Panel (control.exe), nothing worked.
I have also tried to add an manifest file and nothing was solved.
Do I miss something in my code? (examples are welcome).
LPCWSTR("runas") - this is incorrect, you typecast string to widestring, and probably ShellExecute will return error and does not start an application. Specify "L" prefix instead.
Also, you need to split command and parameters, "netsh wlan start hostednetwork" will not work as command name.
Use it like this:
ShellExecute(0, L"runas", L"netsh", L"wlan start hostednetwork", 0, SW_SHOWNORMAL);

C++ Save console output to a text file before quit WINAPI ( No MFC )

I am trying to get my program to log the output of a console application to a text file before it quits. This is a GUI program which launches the console application (tool.exe). The problem is that I am using CTRL + C to quit the console application. This console application cant be altered either. I have tried a few ways of doing this but none have seemed to work ( tool.exe > output.txt ).
Can anyone point me in the right direction of which approach to take ? It would be greatly appreciated.
EDIT:
The file is created but it is empty and does not receive any data. The thing I am after noticing though is if I run the tool from the command line myself, it will work. Eg. c:\>tool.exe > output.txt However this is not working when its executed from my GUI application.
Here is the code I am using to execute the tool:
strcpy (tool, "\" start /D \"");
strcat (tool, toolLocation);
strcat (tool, "\" tool.exe > output.txt\"");
system (tool);
This will run tool.exe and create output.txt fine but will not output anything to the file.
EDIT2:
I think what is actually happening is that because I am using start , the >output.txt is outputing start instead of tool.exe. This would explain why it creates the empty file. Start is just running a fresh command line which is then running tool.exe. The problem is, how do I get around this issue now ?
Try:
#include <signal.h>
void signal_handlerkill(int sig)
{
//Do Soemthing
exit(1);
}
int main()
{
signal(SIGINT, signal_handlerkill); //Connect the interrupt signal (^C) to the function
//Do your code here
return 0;
}
And if that doesn't work, I'd suggest looking here. Specifically:
// crt_signal.c
// compile with: /c
// Use signal to attach a signal handler to the abort routine
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <tchar.h>
void SignalHandler(int signal)
{
printf("Application aborting...\n");
}
int main()
{
typedef void (*SignalHandlerPointer)(int);
SignalHandlerPointer previousHandler;
previousHandler = signal(SIGABRT, SignalHandler);
abort();
}
If you run the application without redirecting to a file, do you see the output you need on the console when you press ctrl+c?
If you don't then there is nothing you can do since you cannot change the application.
Update
What you need is to redirect stdout and stderr to the file. I have never done that but jamesdlin seems to have done that. Take a look at his comment.
What you could try is instead of using start try using cmd.exe directly.
This is the code which managed to solve the problem for me:
char path[500]; //Create character array
strcpy (path, "cd "); //Copy 'cd' into the array
strcat (path, toolLocation); //Copy the path of the tool into the array
strcat (path, " & ip.exe > output.txt"); //Append on the name of the exe and output to a file
system (path); //Run the built array
I am creating a character array and then appending to it. The vital bit here was the & being used in the system call. This is working as an and and first cd'ing to the firectory before executing the .exe.

How to output to the console in C++/Windows

When using iostream in C++ on Linux, it displays the program output in the terminal, but in Windows, it just saves the output to a stdout.txt file. How can I, in Windows, make the output appear in the console?
Since you mentioned stdout.txt I google'd it to see what exactly would create a stdout.txt; normally, even with a Windows app, console output goes to the allocated console, or nowhere if one is not allocated.
So, assuming you are using SDL (which is the only thing that brought up stdout.txt), you should follow the advice here. Either freopen stdout and stderr with "CON", or do the other linker/compile workarounds there.
In case the link gets broken again, here is exactly what was referenced from libSDL:
How do I avoid creating stdout.txt and stderr.txt?
"I believe inside the Visual C++ project that comes with SDL there is a SDL_nostdio target > you can build which does what you want(TM)."
"If you define "NO_STDIO_REDIRECT" and recompile SDL, I think it will fix the problem." > > (Answer courtesy of Bill Kendrick)
For debugging in Visual Studio you can print to the debug console:
OutputDebugStringW(L"My output string.");
If you have a none-console Windows application, you can create a console with the AllocConsole function. Once created, you can write to it using the normal std::cout methods.
If you're using Visual Studio you need to modify the project property:
Configuration Properties -> Linker -> System -> SubSystem.
This should be set to: Console (/SUBSYSTEM:CONSOLE)
Also you should change your WinMain to be this signature:
int main(int argc, char **argv)
{
//...
return 0;
}
The AllocConsole Windows API function will create a console window for your application.
If you're using Visual Studio, it should work just fine!
Here's a code example:
#include <iostream>
using namespace std;
int main (int) {
cout << "This will print to the console!" << endl;
}
Make sure you chose a Win32 console application when creating a new project. Still you can redirect the output of your project to a file by using the console switch (>>). This will actually redirect the console pipe away from the stdout to your file. (for example, myprog.exe >> myfile.txt).
I wish I'm not mistaken!
Whether to use subsystem:console or subsystem:windows kind of depends on whether how you want to start your application:
If you use subsystem:console, then you get all of the stdout written to the terminal. The trouble is that if you start the application from the Start Menu/Desktop, you (by default) get a console appearing as well as the application window (which can look pretty ugly).
If you use subsystem:windows, you won't get stdout/stderr even if you run the application from a DOS window, Cygwin, or other terminal.
If you want the middle way which is to output to the terminal IF the application was started in a terminal, then follow the link that Luke provided in his solution (http://dslweb.nwnexus.com/~ast/dload/guicon.htm)
For reference, I ran into this problem with an application that I want to run in either normal Windows mode or batch mode (that is, as part of a script) depending on command-line switches. The whole differentiation between console and Windows applications is a bit bizarre to Unix folks!
First off, what compiler or dev environment are you using? If Visual Studio, you need to make a console application project to get console output.
Second,
std::cout << "Hello World" << std::endl;
should work in any C++ console application.
Your application must be compiled as a Windows console application.
There is a good solution
if (AllocConsole() == 0)
{
// Handle error here. Use ::GetLastError() to get the error.
}
// Redirect CRT standard input, output and error handles to the console window.
FILE * pNewStdout = nullptr;
FILE * pNewStderr = nullptr;
FILE * pNewStdin = nullptr;
::freopen_s(&pNewStdout, "CONOUT$", "w", stdout);
::freopen_s(&pNewStderr, "CONOUT$", "w", stderr);
::freopen_s(&pNewStdin, "CONIN$", "r", stdin);
// Clear the error state for all of the C++ standard streams. Attempting to accessing the streams before they refer
// to a valid target causes the stream to enter an error state. Clearing the error state will fix this problem,
// which seems to occur in newer version of Visual Studio even when the console has not been read from or written
// to yet.
std::cout.clear();
std::cerr.clear();
std::cin.clear();
std::wcout.clear();
std::wcerr.clear();
std::wcin.clear();
I assume you're using some version of Visual Studio? In windows, std::cout << "something"; should write something to a console window IF your program is setup in the project settings as a console program.
If using MinGW, add an option, -Wl,subsystem,console or -mconsole.
You don't necessarily need to make any changes to your code (nor to change the SUBSYSTEM type). If you wish, you also could simply pipe stdout and stderr to a console application (a Windows version of cat works well).