After finding a bunch of threads on this I did not find any on Windows, only Linux, Ubuntu etc.
In short what I am trying to find out is how to turn canonical mode off so that input in the console results in instant input without having to press enter.
Longer version. This is what I am trying to do right now:
When the PGM is pausing (text based game) the user is asked to enter an arrow key to move the player around on the 2D array. But cin.get(), cin.ignore() and some other things I've tried all require pressing enter before it will continue.
The infamous system("pause>nul"); does actually work, but as I've read in various other places is very bad practice.
This is part of the code. the cout statements are only for testing purpose:
//While loop
if(GetAsyncKeyState(VK_UP)){
cout << "up" << endl;
}
else if(GetAsyncKeyState(VK_DOWN)){
cout << "down" << endl;
}
else if(GetAsyncKeyState(VK_LEFT)){
cout << "left" << endl;
}
else if(GetAsyncKeyState(VK_RIGHT)){
cout << "right" << endl;
}
else{
break;}
//pauze and check for arrow key input here
You can use getch also on windows:
I know it is C, and you got the deprecated warning, but it works...
this code run in a loop till you press Enter:
check what happen when you press an arrow key...
#include <stdio.h>
#include<conio.h>
int main ()
{
int c;
do {
c=getch();
printf("%d\n",c);
} while (c != 13);
return 0;
}
Related
Resolved
I'm using Microsoft Visual Stuido 2017 and built a basic console utility program. When using the debug mode(F5) everything works flawlessly. Then I chose to batch build and see if I could run the .exe. The .exe runs my welcoming message and even greets me with a flashing cursor but won't accept any kind of keyboard input. I try hitting random letters on my keyboard and none pop up; oddly though alt + F4 works so my keyboard likely isn't the issue. I am honestly one hundred percent clueless as to what it might be. It should be noted my save location differs in a few ways. Could it be an issue with my system and not the program?
Screenshot
I have iostream and other appropriate C++ standard libraries included through my header files
int main() {
cout << "Welcome to FTC console commands" << endl
<< endl << "Please enter a command or 'HELP' for help" << endl
<< "You can exit at anytime by typing 'EXIT'" << endl; //Welcome
while (true) { //main loop
league1 = load();
string Input; //Input
cin >> Input;
system("CLS");
if (Input == "EXIT") break; //Checking where to go depending on Input
else if (Input == "ADD_MATCH") addMatch(league1);
else if (Input == "ADD_TEAM") addTeam(league1);
else if (Input == "HELP") help();
else if (Input == "RANK") rankings(league1);
else if (Input == "SAVE") save(league1);
else cout << "Invalid Input... try again or see 'HELP'" << endl;
}
return 0;
}
load(); was referencing a file that didn't exist, so even if it made its own, it lacked the footer I defined and it wouldn't stop reading the document. Simply created the document it was trying to load and added the footer.
my program has read in a large file of words (a dictionary) and inserted them all into a hash table. I am prompting the user to lookup a word and I want them to be able to terminate the program by pressing Ctrl-D. This is what I have tried but when I press Ctrl-D it just gets stuck in a loop printing out what I have in the else statement. I am using Unix. I have attempted looking this up on this website and nothing was working that I was trying hence why I am asking my own question. Any thoughts? PS. The transform is to make the user input all uppercase to match the file I am reading from.
void query(){
bool done = false;
string lookupWord;
while(!done){
cout << "Type a word to lookup or type ctrl-D to quit: ";
cin >> lookupWord;
if(atoi(lookupWord.c_str()) == EOF)
done = true;
else{
transform(lookupWord.begin(), lookupWord.end(), lookupWord.begin(), ::toupper);
cout << endl << "Word: " << lookupWord << endl;
cout << endl << "Definition: " << myDict.lookup(lookupWord) << endl << endl;
}
}
}
atoi(lookupWord.c_str()) == EOF
This doesn't do what you think it does. This checks the return value of atoi() and compares it to EOF. EOF is typically defined as -1. So, the code ends up setting done only when -1 is typed in. Which is not what you want.
std::istream has a convenient operator bool that tests whether the file stream is in a good state. So, all that really needs to be done is:
if (cin >> lookupWord)
{
// Your existing code is here
}
else
{
done=true;
}
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');
}
I'm not new to programming, but I am relatively new to C++. I would like to distribute simple console applications so I can help others as I learn. The vast majority of machines on the campus of my university are windows based, and have the Borland compiler installed by default. I prefer to do my development on a Linux-based system with g++ and other tools. So I'd like to add some cross-platform way of leaving the program running until the user presses enter. That way, the user is able to view the output even if he or she double clicked on the exe rather than running it in the console in windows. To do this, I wrote something similar to:
#include <iostream>
using namespace std;
int main()
{
float val1, val2;
bool wait = true;
cout << "Please enter the first value to add: ";
cin >> val1;
cout << "Please enter the second value to add: ";
cin >> val2;
cout << "Result: " << val1 + val2 << endl << endl;
cout << "Press enter to exit...";
while (wait)
{
if (cin.get() == '\n')
wait = false;
}
return 0;
}
Using the code above, the program exits after displaying the result. However, if you comment out the cin calls, it works as expected. This leads me to believe that cin.getline is picking up my enter key press from my last data entry. I suspect this is due to the tightness of the loop. I have learned that there is no cross-platform sleep function in C++, so that is not an option. What else can I do to make this work?
You can add
cin.ignore(1);
or
cin.ignore(INT_MAX, '\n');
before you call cin.get(). This will ignore the newline left from the user entering the second number or all the characters in the buffer until a newline.
Also you neither need to compare the return value of get to '\n' nor put it in a loop. The user has to hit enter for get to return, so
cout << "Press enter to exit...";
cin.ignore(INT_MAX, '\n');
cin.get();
Is sufficient.
What happens if you do
cout << "Press enter to exit...";
while (wait)
{
if (cin.get() == '\n')
wait = false;
}
Is that the loop is entered, and cin.get() is called. The user can enter any amount of text at the console as he wants. Say they entered
Hello
in the console. Then the user presses the Enter key. cin.get() returns H, and ello\n is still left in the buffer. You compare H with \n and see that they are not equal, continue the loop. cin.get() is called and since there is already text in the buffer, returns e immediately. This loop continues wasting time until it gets to the last character of the buffer which is \n and it compares true with \n so the loop breaks. As you can see, this is a waste of time.
If you do put cin.get() in a loop and compare the return value of it with \n, there is also the danger of cin coming to an end-of-file before an \n is encountered. I believe the effect of this on your program would be an infinite loop, but I'm not sure since I can't try it on Windows.
Also, even though you don't need to use a loop in the first place, you are wasting even more time with a bool because you could reduce the loop to
while (true)
if (cin.get() == '\n') break;
After cin >> you should ignore all the characters in the buffer until the `\n' with
#include <limits> // for std::numeric_limits as indicated by Marlon
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
Then you can wait for the next line with:
cout << "Press enter to exit...";
cin.get();
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;
}