I tried this:
main() {
int a;
cout << "Enter a number: ";
cin >> a;
cout << a;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return 0;
}
But it didn't work.
You don't need to modify your source in order to do this. This tends to be annoying when you exit the program from other places with exit() or abort(). Most IDEs have an option to keep the console open. Are you using Dev-C++ by any chance? It has an option to pause the console. You can find that option in the environment settings. Unless you're using the outdated version of Dev-C++ from Bloodshed. If so, you should update to the Orwell version: http://orwelldevcpp.blogspot.com
The easiest way is to simply place:
system("PAUSE");
wherever you want the pause to be (in your case, in the line above return 0;)
However due to lots of security issues, most would consider the use of system to be bad practice. Instead, try using:
cin.get();
I've always been a fan of using:
std::cout << "Paused. Press Enter to continue.";
std::cout.flush();
std::cin.ignore(100000, '\n');
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();
}
I am trying to get the first program working from "Accelerated C++".
I was having trouble getting the program to stay open without shutting down, so I decided to put a int i = 0; and cin >> i; after main() returns. Unfortuantely, it doesn't seem to take any input, no matter where I put that cin statement.
If it helps, it is using an istream reference to accept cin input. I can't figure out how to enter code on this site.
For most of my adult life, I used system("PAUSE") without any problems to keep the program window open. It's not good for real-time systems, of course, but it's simple and powerful because you're actually running a console command and it can be used to make console scripts.
#include <iostream>
#include <cstdlib>
using namespace std;
inline void Pause () { cout << "\n"; system ("PAUSE); }
int main () { Pause (); }
This solution is not 100% portable, but it will work on PCs. A more portable solution is:
#include <conio.h>
#include <cstdio>
void Pause() {
cout << "\nPress any key to continue...";
while (_getch() < 0)
;
}
cin is good for doing simple things, but what I do is wrap the std library in C functions and use those because it can dramatically improve compile times to hide the std library headers in the implementation files.
The prefered method in C++ is std::getline() using std::string, though many teachers won't let you use that.
With cin, you also have to clear input errors and use ignore() to throw away a specific number of chars.
#include <string>
string foo;
cout << "Why do they always use foo? ";
getline (cin, foo);
cout << "You just entered" << foo;
int bar;
cout << "\nThe answer is because programmers like to go to the bar."
"\nHow many times have you seen foo bar in an example? ";
while (!(cin >> bar)) {
cout << "\nPlease enter a valid number: ";
cin.clear ();
cin.ignore (10000, '\n');
}
My many years of experience have taught me to put the \n char at the beginning of output lines as opposed to the end of them.
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.
Update
I found the cause of the problem. I have been experimenting with the fish shell. I saw the comment that said someone had successfully run my code on a Mac, and decided to try it in a standard bash shell. It worked perfectly. So, no more fish shell I guess. :)
I would still appreciate knowing how and why cin works the way it does. This is the main part of my question.
I have run into a popular problem: using cin in a loop. The code is straightforward, but I cannot find a solution. The answers Google have provided me are varied, but usually involve some combination of cin.clear(), cin.ignore(), and cin.get(). Unfortunately, I haven't been able to find a combination or ordering of those that fix my problem. Moreover, I find it frustrating that I don't have a complete understanding of the function of cin. I'd rather not use trial and error to fix this. I want to understand exactly what's going on.
What Should Happen
When I run my code, I should see a prompt with a list of options. I should be able to type a character which will run one of the options. Then, it should display the prompt again and repeat the process until I select the Exit option.
What Actually Happens
As soon as I run the code, it prints the prompt to the screen an arbitrary number of times and eventually stops halfway through the prompt. Then I am unable to do anything but kill it with ^C.
$ ./run
Choose an option:
[A]dd a score
[R]emove a player
[E]xit
: That is not a valid input.
[repeated a bunch of times]
Choose an option:
[A]dd a score
[R]emove a player
[E]xit
: That is not a valid input.
Choose ^C
$
My Question
What causes cin to do that? As an experienced Java developer (but a beginner C++ developer), I'm familiar with the concepts of buffers and streams and such, but I have no idea how cin works. I know that cin.clear() clears an error state, and cin.ignore() ignores a number of characters in the stream. My Google-fu has thus far been unable to find a concise reference.
Why does cin act the way it does? How should one visualize what happens under the hood when using cin in a loop? What is the most elegant way to implement this infinite menu idea in C++?
My Code
Here is a simplified version of my code, which produces the exact same problem as the full version:
#include <iostream>
using namespace std;
int main () {
//infinite menu
char input;
while(true) {
//prompt
cout << "\n\nChoose an option:\n";
cout << "[A]dd a score\n";
cout << "[R]emove a player\n";
cout << "[E]xit\n";
cout << "\n\t: ";
//input
cin >> input;
//decide what the input means
switch(input) {
case 'a':
case 'A':
cout << "Add a score.\n";
break;
case 'r':
case 'R':
cout << "Remove a player.\n";
break;
case 'e':
case 'E':
cout << "Program Complete.\n";
return 0;
break;
default:
cout << "That is not a valid input.\n";
}
}
return 0;
}
I compile and run with:
$ g++ Test.cpp -o run
$ ./run
I'm running gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00) on Mac OS X 10.8.2.
Do yourself a favour and don't extract tokens directly from std::cin. Instead, read line by line with getline and then interpret each line. Also, you must always evaluate the result of an input operation in a boolean context, or you will not be able to handle arbitrary input correctly.
For a test, your program must survive if you call echo "abc" | ./run. This should always be one of your first tests.
Now, on to the code:
#include <string>
#include <iostream>
int main()
{
for (std::string line; std::getline(std::cin, line); )
{
if (line.empty()) { continue; }
if (line == "A" || line == "a") { /* ... */ continue; }
if (line == "R" || line == "r") { /* ... */ continue; }
if (line == "E" || line == "e") { break; }
std::cout << "Sorry, I did not understand.\n";
}
std::cout << "Goodbye!\n";
}
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;
}