I am currently learning C++ for a programming course. I noticed that my professor's program automatically closes at the end of their program. It usually prompts the user for an input, and then upon entering an input, the program closes. How would I code that? I only know using return 0 gets me "Press Any Key to Continue"
Note: this is a .exe file
If your program doesn't wait for any input, it runs and finally exits from the program. On exiting, the console automatically closes. I assume, to run the program you're clicking on the .exe, as opposed to runnng the program from cmd.exe, or you run the program from visual studio itself without debugging.
You could just put the following line before return 0;:
std::cin.get();
It will wait for some input and then proceed.
use getch(); before return; statement
Return 0 to give "press any jey to continue" is debugger-specific behavior. Running your compiled exe outside the debugger usually wont show that.
The simple code below does a little more than you're asking for (it repeats what you typed in) but still gives the general idea.
#include <iostream>
using namespace std;
int main() {
cout << "enter something" << endl;
string stuff;
cin >> stuff;
cout << "You entered " << stuff << " you insensitive clod" << endl;
return 0;
}
it is easy, at the end of your main() function put this:
int x;
cin >> x;
this define a new variable and tries to fill it with user-input and then the program will not be terminated till the user gives it input. This is how the program reaches the Press any key to continue, finally you exit the program with a 0 argument and the console window will be destroyed automatically since it is the main window of the process.
I recommend to use:
std::cin.clear();
std::cin.sync();
std::cin.get();
cause there may be times when you need to write something and you will need to press ENTER which will make
std::cin.get();
useles. As it will remeber the first time you pressed ENTER and close the window.
Sample:
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cout << "Your name: ";
std::cin >> name; \\ <--Place where you press ENTER <--------------
std::cout << "Hi, " << name << ".";
std::cin.get();
return 0;
}
Related
This question already has answers here:
How to keep the console window open in Visual C++?
(23 answers)
Closed 4 years ago.
My IDE is Visual Studio 2017.
I am pretty new in C++ programming so I need a help about understanding principles of creating a new C++ project in Visual Studio.
So, in my first solo attempt i just chose a empty project option and afther that i chose to add new item and i write this sample code:
#include <iostream>
using namespace std;
int main()
{
return 0;
}
Afther this step and afther steps with compiling, building and a starting without debugging i did not get any message or consol window with time of code execution or option for entering any key for ending.
What is needed for getting this kind of information at the end of code?
You shouldn't use system("pause"); you can read here why. It's platform dependent and adds a huge overhead loading all the Windows specific intstructions.
So you should choose nicer alternatives: std::cin.get() for example. Which will work most of the time. Well, except if there had been input before (std::getline or std::cin). If you're creating a program with user input - use std::cin.ignore() twice to guarantee a "press enter to continue" effect:
#include <iostream>
int main() {
int a;
std::cin >> a;
std::cin >> a;
std::cin >> a; //etc
std::cout << "press enter to exit - - - ";
std::cin.ignore(10000, '\n');
std::cin.ignore(10000, '\n');
return 0;
}
also please don't use namespace std; read here why.
If you don't like this 3-liner (because it looks ugly) you can pack it in a void function and treat the whole thing as a black box:
void pause() {
std::cout << "press enter to exit - - - ";
std::cin.ignore(10000, '\n');
std::cin.ignore(10000, '\n');
}
int main(){
pause();
return 0;
}
Converting Blaze's comment to an answer
Go to Tools->Options->Debugging and look for an option called "Automatically close the console when debugging stops" and ensure that this option is not activated.
I did not get any message or consol window with time of code execution or option for entering any key for ending
Because you didn't ask for it.
What is needed for getting this kind of information at the end of code?
To perform input (see std::cin and operator<<) and output (see std::cout and operator>>). Example:
#include <iostream>
int main()
{
std::cout << "Press enter to terminate\n";
std::cin.get();
}
with the following code
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Insert number: " << endl; // prints "Insert number:"
cin >> num; //Reads num
cout << num; //prints num
system("PAUSE");
return 0;
}
i get the following result in the internal console of eclipse:
Insert number: //code in line 6
3 //code in line 7 (Input)
Press any button... //code in line 10
//empty line after pressing any button
3 //code in line 8?!?!?
And I have no idea why this is happening. It looks like eclipse just twists the execution of the code. But why and how could i solve this problem?
It's called buffering. Output to std::cout is buffered, and won't be displayed unless the buffer is flushed (which happens at program exit) or you explicitly flush it with the flush or endl standard I/O manipulators.
That the output of the PAUSE command is displayed is because it bypasses the std::cout buffering of your process, and either writes directly to the console window or because it flushes its own internal buffers (the PAUSE command will be run as an unrelated process, with its own possible buffering).
I'm working on a simplish game (this isn't the whole code, just the bit that I'm having issues with) and I've run into this issue; After the condition is furfilled, it goes back to the start and it offers me to reenter the string, however, whatever I enter, I just get 'Not Valid'. Does anyone know why? I'm using the GNU C++ Compiler.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string command;
mainscreen:
cout << "blab";
getlinething:
cin.ignore();
getline(cin, command);
if (command == "task")
{
goto mainscreen;
}
else
{
cout << "Not valid.";
goto getlinething;
}
return 0;
}
When I run your code with a debug print it shows that each time you read a new command you are loosing the first char of the string. In fact, when I remove your cin.ignore() it works fine.
Also, have a look at this while to see if it fits your needs:
cout << "blab";
while(1){
getline(cin, command);
if(command == "task"){
cout << "blab";
getline(cin, command);
}
else{
cout << "Not valid.";
}
}
For debugging purpose at least, why not do
cout << "'" << command << "' Not valid" << endl ;
Alright, I tested it out. Without cin.ignore(), I cannot enter the data into the string at all.
The first time I enter it captures everything. So if I wrote task, the string would say 'task', however the second time I entered it, it would say 'ask'. I don't really know why it's doing that.
The cin.ignore() line will always discard one character by default (unless it encounters EOF, which would be a fairly deliberate act on cin).
So, let's say the user enters task and then hits the enter key. The cin.ignore() will discard the 't', and the command string will contain "ask". If you want to get a match, the first time through, the user will need to enter ttask. The newline will be discarded, in either case. The same will happen until a match is encountered.
Hi I'm a highschool student in need of help. I am interested in C++ as I wish to become a programmer one day. I started using Visual Studio for C++ and I'm running a few simple lines of code. But everytime I press (Ctrl + F5) or Local Windows Debugger it shows my line of code but it closes out immediately after it runs, making it near impossible to read. The code is the classic "Hello World!" code. Maybe it has to do something with return 0;?
EDIT: Here's my code.
#include <iostream>
using namespace std;
int main()
{
int mark = 90;
if (mark < 50) {
cout << "HES OLD" << endl;
}
else {
cout << "Hes not old!" << endl;
}
}
When making console applications, I use the following lines at the end of my main function:
std::cout << "\nPaused. Press Enter to continue.\n";
std::cin.ignore(100000, '\n');
The idea is to display a prompt and then wait for the Enter key to be pressed.
Many of folks here are telling me to stop using clrscr(), getch() etc. and I have started learning C++ with the standard library and now that I want to follow the standard library how would I stop the output from immediate exit after run?
include <iostream.h>
include <conio.h> // Instead of using this
void main(){
cout << "Hello World!" << endl;
getch(); // Instead of using this
}
You can directly run the binary from command line. In that case after the program is finished executing the output will still be in the terminal and you can see it.
Else if you are using an IDE which closes the terminal as soon as the execution is complete, you can use any blocking operation. The simplest is scanf (" %c", &dummy); or cin >> dummy; or even getchar (); and what Adriano has suggested. Although you need to press Enter key, as these are buffered input operations.
Just replace getch() with cin.get() like this:
include <iostream>
using namespace std;
void main()
{
cout << "Hello World!" << endl;
cin.get();
}
For more details see get() function documentation. Just for reference you may do this, for example, to wait until user pressed a specific character:
void main()
{
cout << "Hello World!" << endl;
cout << "Press Q to quit." << endl;
cin.ignore(numeric_limits<streamsize>::max(), 'Q');
}