I installed Codeblock a week ago and have not changed any setting. I created a simple console application and when I clicked build and run it display my output for like milisecond and disappear... It used to stay forever until I exit it. Anyone know why is this happening? In the Build log tab it says "Process terminated with status 0 (0minnutes, 0 seconds)
You don't have any problem actually, neither in your Codeblocks Application nor in your code, But codeblocks doesn't wait for you to close its console window manually, It automatically does it.
You've 3 ways, choose that suits you better
Go to Menu Bar and toggle 'show output window'
Alternatively you can append a C++ code that waits for an event to happen, so that you may get enough time to watch your Output.
You can use the code which I've given below
It will be definitely good if you choose to see your output message through debugging(Step Over). It will also improve your debugging skills.
If you want to choose second approach then append following code in your application
#include<conio.h>
int main()
{
// After your code - write
getch();
return 0;
}
Note:- I believe you're using codeblocks on Windows Platform, this code will work fine on windows, but <conio.h>
won't be available to you if you want to port your program from Windows to Linux
I'll recommend you to give them preference in this order [3 > 1 > 2]
for those who may encounter this error:
all you need to do to make the console not dissapear is this:
go to project properties.
click on build targets
there is an option below console application "pause when execution ends"
check it and you are good to go!
Hope this helps
Use :
#include <iostream>
//...other includes....
int main()
{
/*Your Code */
//...
std::cin.ignore(); //wait for Enter, will makes the console to stay.
}
You may be clicking on the red arrow, however click on the "build an run" arrow instead, which has a little cog and a green arrow.
Solution if you are copying and pasting input: For me, the issue was that I was copying and pasting my input file from the web. Presumably, this copied some invisible characters, such as a return, which my program registered as the user having pressed any key to continue. The solution I used was to download the file to my computer, then run my program in command prompt, piping the input into the .exe file in the following manner:
C:\Project Directory> myProgram.exe < myInputFile.txt
Many of my professors recommend running programs from the command line, and I advise using this tactic as it is quick and lets you skip manual typing. Also, you can save the output of your program to a desired file, rather than having it print on the command line, by doing the following:
C:\Project Directory> myProgram.exe < myInputFile.txt > programOutput.txt
Hope this helps.
Related
We've got a task to basically write up a code that accepts input from the user, and then multiplies that input by itself. However, for some reason, when I run the program, it'll accept an input, then end, without showing the product at all.
For reference, here's the code used.
#include<iostream>
using namespace std;
int main()
{
double dValue1, product;
cout<<"Please input your daily budget.\n";
cin>>dValue1;
product=dValue1*dValue1;
cout<<product;
cin.get();
return 0;
}
EDIT: For anyone interested in a quick (but not permanent) fix to this problem, I've been adding #include<stdio.h> and using getchar(); getchar(); to at least allow me to see the output !! Hope this will help anyone struggling like I was. ^w^
This has everything to do with how you are running your program.
On Windows, the system recognizes that the program is tagged as needing an output terminal and creates an instance of the Windows Console for you.
Your program then runs without problem, printing its output to the console, then terminates.
Since the process terminated, Windows cleans up and closes the Windows Console window that was attached to your (now non-existing) application. Your user never gets the chance to see the output.
The correct way to fix this is to simply run the program from the Command window directly. Use Explorer to navigate to the executable as usual, but instead of clicking on the file you should click on the Navigation Bar and type cmd and press Enter.
This gets you a Windows Console opened to the folder containing your executable. Type its name and press Enter to see it run. For example, if your program is named "quux.exe" then type quux and press Enter.
When you are done with the terminal window, just close it by clicking on the "X" button like with any other Windows application.
Why not use getch() or something like that?
Because it assumes that your user is a human typing things in. That may not be the case, and programs that require a human to be present when not needed are quickly discarded for programs that don't.
I am trying to write up a C++ program for a class using XCode. One of the things I wish to do, is to simply clear the screen. I've looked into how to do this, however the catch is that the code needs to run on both a Windows and Macintosh computer. I've looked at some other similar questions, but none of the answers help me. I know there is no "screen" but I want the system to clear the output window. I know that the command system("clear"); does what I want it to, but when XCode tests the program, instead of clearing the screen it prints TERM Variable not set
I've tried opening up the terminal and typing clear and it does in fact respond the way I want it to, so why doesn't the 'terminal' inside of XCode do the same? I just want to get the output window in XCode to respond to clear the same way that the terminal already does.
Here is something I have already tried;
I went to the terminal and ran echo $TERM, to which the terminal responded xterm-256color. I then went over to XCode and opened the "Scheme" settings, and found an Environment Variables setting under "Arguments". I added a variable (to the blank list) called TERM and gave it value xterm-256color. Upon running the program again, the output displays ¿[H¿[2J in the output window, positioned where the TERM Variable not set used to be printed.
Last thing, as a reminder, I cannot change the source code from the way it is now, or it could cause errors when the program is run on a Windows machine.
It does not work because you are "lying": The terminal in Xcode is not a xterm-256color, but it is dumb terminal. More precise, the display represents a NSTextStorage that collects stdout and/or (depending on target switch) stderr.
A dumb terminal is not able to clean the display. If you want to change this, you can write a plug-in similar to Xcode-Colors what adds the ability to understand ansi color codes.
However, if your requirement that the code simply run at Windows and OSX, you may stick with your solution system("clear"), since it works prefectly in the "normal" OSX terminal.
My application is a GUI app that has helpful (though optional) information through the terminal (via cout).
In Windows I either have a console appear (by compiling as a console app, or allocating it dynamically) or I don't.
My intention is to make use of the console IF it is being run from the console, but ignore the console completely if it was not. (Essentially what happens in Linux and OS X).
I do not wish to redirect to a file (and in the case of using cin, this is not a viable solution anyway).
Is there a way to attach a GUI app in Windows to the console it is run from, if and only if it is run from a console?
and in the case of using cin, this is not a viable solution anyway
This is the killer detail in your question. It is simple on paper, just first call AttachConsole(ATTACH_PARENT_PROCESS) to try to attach to an existing console. That will fail when your program got started from a GUI program like Explorer or a desktop shortcut. So if it returns FALSE then call AllocConsole() to create your own console.
Using cin is a problem however. The command processor pays attention to your EXE and checks if it is console mode app or a GUI app. It will detect a GUI app in your case and then doesn't wait for the process to complete. It displays the prompt again and waits for input. You will then also wait for input but you'll lose, the command processor got there first. Your output is also intermingled with the command prompt, the easy problem to solve.
There's a simple workaround for that, your user should start your program with start /wait yourapp to tell the command processor to wait for the process to complete. Problem is: nobody ever uses that. And the user will not realize what happens when they type input, intending it to go into your program but it is actually interpreted by the command processor. Producing a mystifying error message or formatting the hard drive.
Only two good ways to solve this unsolvable problem. Either build your program as a console mode app and call FreeConsole() when you find out you want to display a GUI. Or always call AllocConsole(). These are not great alternatives. The first approach is the one used by the Java JVM on Windows. One of the oldest bugs filed against the JVM and driving Java programmers completely batty from the flashing console window.
The third alternative is the only decent one, and the one you don't want, create another EXE that will always use the console. Like Java does, javaw.exe vs java.exe.
A trick is possible, you can rename that file from "yourapp2.exe" to "yourapp.com". It will be picked first when the user types "yourapp" at the command line prompt, a desktop shortcut can still point to "yourapp.exe". Visual Studio uses this trick, devenv.com vs devenv.exe.
You can check CONSOLE_SCREEN_BUFFER_INFO (via GetConsoleScreenBufferInfo) on startup to determine if you've been run from within an existing console. If the buffer's position is 0,0, you were run from outside of the console. For details, see this Microsoft Knowledgebase Article which describes the process.
In order for this to work, you need to compile your application as a console application (using /SUBSYSTEM:CONSOLE), and then detach yourself from the console if the application started a new console (buffer at 0,0). This will cause the program to properly "attach" to the calling console when launched from a command line.
As others have pointed out you have to create a console app and a window app. So, you'd end up with console.exe and app.exe. To make it less obvious at the command-line, you can take advantage of the PATHEXT trick like devenv does. cmd.exe treats a file as a command if its extension is in the PATHEXT environment variable. COM is there by default so you could rename console.exe as app.com, allowing the command app to start the console app attached to the current console.
Note: Of course, a console app can show a GUI if desired.
The difference in the build between app.com and app.exe depends on your build system but it could just be the one attribute that sets the output type. With msbuild (for .vcxproj files), it's just a matter of another build configuration.
you can create an application in console that get a line using argc and prints it;
////
int main(int argc, char *argv[])
{
//here print argv....using cout or printf
}
save the file as console.exe in the folder of your app.
now in your app if you want to see any line in console you can call the command
system("console.exe this is the line i want to print and see in console");
A command line program always closes the window after it has finished executing. I know you can use cin.get(); to wait for the user to enter input. Is there a way where the user could press any key (instead of entering something then pressing enter) to close the program? I don't want to use system("PAUSE") as it's Windows specific and slow.
I want it to pause so that the user can see it completed successfully and other details. It would probably not be run from an already open command line and the executable would be double clicked to run.
Yes. "system("PAUSE") is one way. A simple "getchar()" or "cin" should be absolutely equivalent :)
It's an option with the OS and not in C/C++. It needs to control how the Terminal open and close.
Just like if you called a batch or a command line app.
It's too platform dependent to post a code or config here (basically a Console GUI application with onClose statement in our IDE)
After compiling console programs the console window closes immediately after running. What is the best practice for keeping it open? I've searched google loads, I'm used to codeblocks where you don't have to worry about it, but, I want to mess around with Visual Studio a bit and with VS, my console closes. All over the interwebz there are several different ways to keep it open, however, I've read that most of them are bad coding techniques. What is everyones preferred method?
When I'm using Visual Studio and I don't need debugging I just run it using Ctrl+F5 keystroke – and it prevents console from closing.
Since you always run in the debugger, set a breakpoint on the return statement from main().
The debugger is your best friend, learn (and learn early) to use it to your advantage at every opportunity.
Run your program in a console, which would be the expected way of running a console program ...
Alternatively, you can make a little batch file to execute your program that would have:
REM batch file to launch program
yourprogram.exe
PAUSE
and the PAUSE cmd.exe command will ask to user to press any key.
I tend to use system("PAUSE"); which gives you a
Press any key to continue . . .
message.
cin is grossly inelegant but easy for the forgetful to derive:
{
char c;
std::cin >> c;
}
That holds the window open until you type a character /* edit */ and hit enter.
std::cin.get() will close the window the moment you type a character, which, depending on how easily you become habituated, runs a marginally greater risk of "whoops, I wish I hadn't closed that!" than the two-keystroke operator>>(istream &).
Both differ from a system("pause") in that they return in a program-accessible way the value of the character you typed, so, if as not infrequently happens, one kludge leads to another, you can write a switch statement based on what you typed to (for example) exit immediately, write some values to a log, run it again, etc.
I use:
cin.get()
I heard it was less costly than system("PAUSE") and it works on POSIX systems too.
There's a great link that goes into detail about this.
Resist the temptation to do anything. Well behaved command line programs exit when they've finished running reporting a status via their exit code. This enables them to be scriptable and 'good citizens' in automated environments. Even in an interactive environment, why force the user to make an extra key press just because of your debugging environment?
If you run, rather than debug then Visual Studio will open a console windows that pauses after your application exits so that you can still view the output. I don't know why the behaviour is different when you debug, perhaps because you have breakpoints available so if you want to see the output at various stages you can place breakpoints after the relevant output statements, or at the end of main or enable various 'stop on exception throw' options.
Whatever the reason, I've never felt compelled to compromise the behaviour of my application just to enhance my debugging experience.
A very common one is to just put in code to read a key from the console after your main application code closes. The keystroke read in just gets thrown away, but it holds the console open.
It's not pretty, necessarily - but I often do this wrapped in a debug define, so during debugging, the console is held open. During release, I'm usually not running inside VS, and when run from a command line, this is no longer an issue.
The "don't do that" responses in this thread may seem curt, but they're fairly sensible. I happened across this question because I'm debugging a gtest suite that used to run fine, but now crashes mysteriously when launched. When run from the console, it pops up a dialog saying "blah.exe has stopped working"; but, when run from the debugger, the console pops up momentarily, vanishes, and the program exits with 0 status.
I should have been thinking about how odd this difference in behavior was, but instead I was like: "Aw, man---I gotta make that console window stay up so I can see what it says." Right?
It turns out that the machine I'm working on (a colleague of mine's) had the 'Command Arguments' for the debugger set to '--gtest_filter=*testMsg*'. I noticed this right away, too, but it never occurred to me that all the tests matching the filter had been renamed in a recent commit. So, when launched from the debugger, gtest wasn't finding any tests to run and was simply exiting. Another 90 minutes of my life I'll never get back. (-_-) I could have ditched this tar baby a lot sooner if my knee-jerk reaction hadn't been to think I needed that console window to stay open in order to solve the problem...
Call this function before you return at the end of main:
void onEnd()
{
printf("Press any key to exit...");
_getch();
}
You can specify that the executable is a Console app, not a Windows app, at least in VS2017. This makes your application run in a "Microsoft Visual Studio Debug Console", with "Press Any Key To Close This Window" appearing at the end of the console output:
Right click the project to bring up Properties.
Linker > System > Subsystem > Select "Console".
Press Apply before closing.