Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I've recently read about how BAD system("PAUSE") is. I tried cin.get() but I don't know how to use it to pause a program. Other posts say to put a breakpoint after the statement. But I have no knowledge on how to do that. Any suggestions on how to pause my program? An example would be really appreciated.
Assuming that you are indeed working on Windows, the worst thing about system("PAUSE") is that it betrays a fundamental misunderstanding of your operating system's architecture. You do not need a code replacement for system("PAUSE"), because the code is the wrong place to solve the perceived problem.
Beginners like to put system("PAUSE") or even a portable alternative like std::cin.get() at the end of a program because otherwise "the window disappears" as soon as the program ends. Such logic, however, is deeply flawed. The window which you probably see while the program runs and which has made you ask this question is not part of the program itself but part of the environment in which the program runs.
A typical console program, however, must not assume details about the environment in which it is executed. You must instead learn to think in more abstract terms when it comes to input and output via std::cout and std::cin. Who says that your program is even visible for a human user? You may read from or write into a file; you may use pipes; you may send text to a network socket. You don't know.
#include <iostream>
int main()
{
std::cout << "Hello world\n"; // writes to screen, file, network socket...
}
Opening a graphical window and displaying text output on the screen is not in the scope of your program, yet using system("PAUSE") assumes exactly that one single use case and breaks all others.
If you use an IDE like Visual Studio and are annoyed by the fact that pressing F5 eventually results in the window disappearing before you have had the chance to see all output, here are three more sensible alternatives than manipulating the program itself:
Demystification. Observe that what Visual Studio really does is invoking the Visual C++ compiler behind the scenes in order to create an *.exe file. Open your own console window with cmd or with Tools > Visual Studio Command Prompt, locate the directory of that *.exe file and run it there (you should eventually also learn to start the compiler without Visual Studio's help, because that will give you a deeper understanding of the C++ build process).
Press CTRL+F5.
Place a breakpoint at the end of your code. Read the documentation if you don't know how.
I got one step closer, cin.ignore, but the user can only press enter if he/she wants to continue.
Example with cin.ignore():
#include <iostream>
int main()
{
cout << "Press enter to continue!\n";
cin.ignore();
//do something
return 0;
}
When you press enter it advances and does whatever you want it to do.
Related
I just started learning c++ and while reading the c++ tutorial in http://www.dev-hq.net/c++/1--the-basics i saw that writing a c++ program in some text editor is different from writing one in visual c++. It said something like "Visual C++ will require some sort of application pausing before the end of the 'main' function in most cases as it generates a window which will disappear after execution".
what does this mean?
Short Answer: It isn't mandatory. The site suggests so that the output in the console window can be seen before the program exits (thereby closing the window).
Long Answer: If you're using an IDE to develop a C++ or C program with no GUI, the output is shown by the IDE by launching the console/terminal window (also called the command prompt). This window is shown as your program is started and closed immediately when your program ends. Say if you just print "Hello, world!" and don't give any pause, the terminal window would open, show Hello, world! and immediately close, all in a blink of an eye. So it's customary that a pause is inserted in the end. This problem isn't seen on all IDEs; some show the output in its own integral window, some insert the pause behaviour through script, etc.
It is to be understood that this is just a hack to make the window stay and making a blocking call to do so is useless from the program's viewpoint. Also don't use system("pause"); as it has issues, apart from the fact that it's not portable and works only on Windows platforms.
#include <iostream>
#include <limits>
int main()
{
std::cout << "Press ENTER(s) to exit...";
// flush data in cin's buffer
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// blocking call to fresh input from user
std::cin.get();
}
This would be a portable way i.e. irrespective of the platform you're using it will work.
An alternative is to use getchar (not the similarly named getch) which is portable as mandated by ISO C Standard but it has its quirks.
Another way would be to put a breakpoint as suggested by Raja. It'll also get your feet wet in learning the debugger, an essential tool in programming.
To avoid the issue altogether run the program yourself from the console window. Although sometimes it may get a bit tedious for a beginner, hand compiling code and running it yourself without an IDE gives you more insight and is a good learning experience.
I'd still recommend hand compiling or the debug breakpoint methods instead of injecting a fake pause/blocking call in the program; notice that the input received from the user is just ignored and never used in the program further down the line and thus is redundant from the program's standpoint, hence the recommendation to not use it.
When you use "Run Project" (Ctrl+F5 in the classic Visual-C++ key binding, not just F5, which is "Debug Project"), Visual Studio will keep your console window open until you press a button.
It's only when you use "Debug Project" that it doesn't. This makes sense, because you generally only want to use that option (which has a much longer startup and shutdown time and runs slower) when you're actually hunting a problem, in which case you probably have breakpoints set in your program and can simply set one on the last line of main().
So all the proposed workarounds, and the flames about Visual Studio, are simply unnecessary and wrong.
It just means that the executable window will close as soon as it's done executing.
I would recommend using a simple getchar(); statement from the standard library (<iostream> or <stdio.h> header) before you return 0;. This means you will have to press a key for the window to close. As you mention Visual C++, system("pause"); will work as well before the return on Windows systems.
Of course, if you return from main earlier (common with error codes, unhandled exception, or an exit call somewhere), you likely won't get to that pausing mechanism. As you are just starting out, it is unlikely you will run into that stuff for now though.
Running your program from the command line will work as well to see the output.
Here is something I use to pause my console applications and let me see the results:
void waitForUser()
{
// if for some reason cin is in invalid state
// we need to clear it
std::cin.clear();
// if we used cin to input something it is likely to
// contain trailing \n symbols , we need to get rid of them
std::cin.ignore( std::cin.rdbuf()->in_avail() );
// we wait for a user to hit Enter here
std::cin.get();
}
Just put a call to this function at the end of main
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
So I am an amateur programmer, currently enrolled in my second semester of C++ (yesterday we learned about structs just to give you an idea of what I know...).
I am creating a simple program to help me file documents at my internship.
I am using a system command(yes I know its dangerous and a big security risk), to open a pdf in firefox so that I can see the file and know where to put it.
I have successfully opened firefox and opened the pdf.
However my program stops running until I close firefox.
My question is how do I continue my program at the same time?
Is there an easier way to display a pdf in an executable?
edit:
Here is the function I use to open the firefox window with the pdf in it:
void openPDFBrowser (char array[])
{
ofstream outFile;
outFile.close();
outFile.open("PDF_browswer_handleScript.txt") ;
if(outFile.good())cout<<"OUTFILE GOOD" << endl;
outFile << "system("<<array<<")"<<endl;
system("PDF_browswer_handleScript.txt");
outFile.close();
}
the .txt file contails: firefox C:\Scans\Attorney.pdf
where firefox references a .bat file which contains the location of firefox.exe
I will take any suggestions
it just seemed easier to use an external browser to handle the display of the pdf file, although I'm still working out this threading idea
system is a blocking command - meaning it will stop your execution until that function returns. The only way to do this is to create a separate thread (or to fork a separate process, as noted by Chris Hayes), and to run the system (or CreateProcess, or exec) inside it, allowing main thread to continue.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to stop C++ console application from exiting immediately?
I'm currently learning C++ and cant figure out how to stop the application from exiting when I want to show the user some data, and have time to read it. How may i do that?
Update: Somehow I pause the application and when the user click a button it exits.
I assume you're on Windows.
This can turn into a long debate, but generally there are two main ways people do it:
(recommended) Add cin.get(); to the end of your program. This will cause your program to stop until the user hits enter, then it will continue and quit.
This will work on Windows and Linux.
Add system("PAUSE"); at the end of your program. This will cause your program to print something like Press any key to continue. . . and when you hit a key, the program will continue and quit.
There is a chance that the PAUSE command doesn't do that and can order pizza, launch the missiles, or something else.
This only works for Windows but you won't need it when you go to linux anyway.
std::cout << "Press enter to exit" << std::endl;
cin.get();
exit(1);
If you want to pause your program until the user presses a key, you can use cin.get(). But really, the program should terminate when it's finished. Otherwise, it's useless in pipelines and the like.
If your program's window goes away when it's finished, then something is wrong with the way you launched it. Whether the window stays when the program is done is up to the thing that launches the program and sets up the window, not the program. This problem is usually caused by launching CLI programs from a GUI. If you want to launch from a GUI, write a GUI program. Otherwise, launch terminal programs from the terminal.
Do not use system("pause");. It makes your program unportable. And if you ever run it on a system whose pause command does something other than what you want, you may have a very angry user on your hands.
Do not use getch. That's a Windows console function and a Curses function. It's not part of C++. (Unless you are specifically developing for a platform that has this function and you are sure it does what you want. But this one function would be a really silly reason to make your program unportable.)
Im currently learning c++ from a book called 'Ivor Hortons Beginning Visual c++ 2010'.
In all the examples i've attempted so far I've had to use getch() to hold open the command prompt, and sometimes remove the return 0 statement from the end of the main method.
Is this a vagary of windows 7 and will it cause problems further down the line? It's no problem doing this at the moment but since this is not included in the book I was wondering if it might be something I've set up wrong.
Many Thanks :)
Use _getch() in place of getch()
getch() is not operating system specific, but it is not directly portable. The preferred method for doing this in C++ is to use std::cin.get();.
The main function can return 0 implicitly (you don't need to actually have that code, see below).
int main()
{
// valid, return 0 implied.
}
See this question for more details about the implicit return 0 from main.
When a program ends, any resources created by that program including the terminal window will be released. By using getch you prevent the program from ending. This is normal behavior and should continue to work that way until Windows is a distant memory.
If you start the program from within an already existing command window, the window will not close because it wasn't created by the program.
First, getch() isn't a standard C or C++ function. Even under
Windows, I think its use is deprecated; its semantics go back to CP/M
and early MS-DOS.
Secondly, it really isn't necessary, at least not for console apps (and
I don't think it's available for non-console apps). If you're running
the program from a console window, the window stays open. And if you're
running it from Visual Studios, it's trivial to set a breakpoint on the
return statement, which blocks the program, and keeps the window open
(although there's really no reason for the IDE to close it just because
your program has terminated).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have created this program:
//Includes....
int main()
{
ifstream readfile("File.txt");
string str;
while(1)
{
getline(readfile,str);
system("cls");
Sleep(10000);
}
}
It's just a program that reads every 10 seconds a line from the file "File.txt"
I want to make it work on background,how can I do that?
If this was UNIX you would run the program from the shell with an ampersand "&" after the program name.
This sample hide console windows for you :
#include "windows.h"
#include fstream
#include string
#include stdio.h
using namespace std;
int main()
{
WCHAR path[260];
GetModuleFileName(NULL,path,260);
HWND console = FindWindow(L"ConsoleWindowClass",path);
if(IsWindow(console))
ShowWindow(console,SW_HIDE); // hides the window
//---------------------------------------------------
ifstream readfile("File.txt");
string str;
while(1)
{
getline(readfile,str);
system("cls");
Sleep(10000);
}
//----------------------------------------------------
if(IsWindow(console))
ShowWindow(console,SW_SHOW); // shows the window
}
Platform dependent. But I think you are using windows because of the "cls" command.
Why cant you just start a new command prompt and execute the correct .exe file. Then just minimize the program and do what you are supposed to do. If want to automate the startup phase (like cron in linux/unix) use the built in scheduler for windows.
If you want a (non-service) program that doesn't use a console window or any other windows at all, change main() to winmain(). Getting at command line arguments is a little more involved though.
I'm sorry, but I'm not sure I know what you mean... as far as I know (please correct me if I'm wrong) there is no way to run a simple C(++) program without a console window. However if you want it to "sleep" in a way that uses near no resources, then that can be achieved by checking current time and compering it with the time when you completed your last read.
Sleep function usually uses more resources than this, however it works just as well, so if resource cap isn't very very important then it will do just as well.
Hope this helped.
If you're launching your program from a Dos console, you can use the command start \B myprogram.exe, which is more or less equivalent to the unix ampersand. However, you'll need to keep the console open to keep the program running.
Another solution is to convert your application into a windows service, but then you'll have to rewrite (or wrap) your application.
If you want this because you're logging some kind of output and want to view the changes you could just use an editor such as TextPad which will automatically reload the file when it changes.
However you've not specified why you want this so this may not be appropriate in your case.
The proper way is to use a Windows service, there is enough information on Google on how to do this.