I'm working on a project where I want to have delays in the output in C++ on UNIX. Here's an example of what I'm talking about:
cout << "You walk through the darkness, no sign of life in sight" << endl;
usleep(1000000);
cout << "What would you like to do?" << endl;
cin >> userCommand;
Now, if the user types something while the usleep is ongoing, it goes into the cin statement later, which, while I can give appropriate error messages, I'd rather not deal with. Additionally, sometimes I want certain things on the screen, so I don't want the user to just hold down enter and clear the screen.
Is there any command which fully blocks user input from even interacting with the screen? Something that I could deactivate right before my cin statement and reactivate right after the cin statement?
Thanks!
you can use
#include <stdio.h>
...
cout << "You walk through the darkness, no sign of life in sight" << endl;
getch();
cout << "What would you like to do?" << endl;
cin >> userCommand;
getch() block until you press a key
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 months ago.
Improve this question
Hey so I only started C++ 2 days ago, so please try to keep the answer simple, otherwise probably won't understand it, thanks!
I tried to make a basic program where a program asks for a word, then counts the letters in said word. It then tells asks if you want to know the letter in any given position of the letter. Im making this because I thought I would learn better if I just tried making something basic rather than endlessly watching videos on it.
I ran into a problem with the asking the user part of the code. I want to have it check whether the user typed Y or N, and if neither, repeat asking until either Y or N is inputted. I tried using goto, but I could not get it to work despite checking online tutorials on how it should work. If anyone could help that would be greatly appreciated :).
When run, it does the following: enter image description here
The code is below, thank you for reading:
#include <string>
using namespace std;
int main(){
string text; //variable for the word to be measured
int letter; //variable for the placement of the letter in word
string confirmation; //variable for Y or N
cout << "This program counts letters in a word \n\n";
cout << " Please type a word for me to count: \n\n";
cin >> text;
cout << "\nYour word has " << text.length() << " letter";
if (text.length()>1){
cout << "s"; // Checks whether to put an s at the end of the prev. sentence for a plural or not
}
cout << "\n\nThis is what you typed by the way: " << text << "\n\n";
cout << "Would you like me to find the letter in any given position in the word? \n\n If yes, type Y. If no, type N: \n\n";
cin >> confirmation;
check:
if (confirmation == "Y"){ //Loops until one of these are fulfilled
cout << "What position's letter would you like me to find? \n\n";
cin >> letter;
cout << "\n" << text[letter-1] << "\n\n";
cout << "Thanks for using me, have a nice day";
} else if (confirmation == "N"){
cout << "\nAlright have a nice day";
} else {
goto check;
}
return 0;
}
First, goto-Syntax is something you do not need to learn as a beginner. In 99.99% there are better alternatives than using goto, so until you are very advanced, just pretend that goto does not exist in C++.
Second, the goto in your code works. It is just that if the user answers something different than "Y" or "N", your code will infinitely loop between the label check: and the goto check statement, as there is no way that confirmation can change in between.
Last, here is an example how to better do this, using a while-loop.
cout << "Would you like me to find the letter in any given position in the word? \n\n If yes, type Y. If no, type N: \n\n";
cin >> confirmation;
while (confirmation != "Y" && confirmation != "N") { //Loops until one of these are fulfilled
cout << "Please answer Y or N.\n";
cin >> confirmation;
}
if (confirmation == "Y"){
cout << "What position's letter would you like me to find? \n\n";
cin >> letter;
cout << "\n" << text[letter-1] << "\n\n";
cout << "Thanks for using me, have a nice day";
} else {
cout << "\nAlright have a nice day";
}
Now I want to output the following "You Paid:" // and then after this text user should put a number after which I want this word "Dollars." appears directly without pressing enter
is this possible and how
It's not really possible, since you need to press enter to tell the program that the input is ready. However, you could do something like this:
int payment;
cout << "You paid:" << endl;
cin >> payment;
cout << payment << " Dollars." << endl;
That way, if you input, for example, 5, the console will look like this:
You paid:
5
5 Dollars.
I am trying to make a program where the user tries to guess a randomly generated number; basically, a classic number-guessing game.
My program is running pretty well but I can't find out how to ask the user to play the game again if the guessed number is correct, and also how to keep asking the user for guesses if the guessed number is incorrect.
Can somebody help me accomplish this?
You can use a while loop to keep asking the user for input, as so:
int guess, answer = rand()%10;
while(cin >> guess){ // keeps on asking the user for input
if(guess > answer){cout << "Too high!" << endl;}
else if(guess < answer){cout << "Too low!" << endl;}
else{
cout << "Good job!" << endl;
break;
}
}
I appreciate the help. I am really bad at c++ and i like constructive criticism. im building a text based game and im currently setting up all the functions and systems. my problem is that i need a way for the user to be able to, at any time, type in somthing like "stats" and have them printed on the screen. currently i do not know how to do that. i dont know if this is possible but would i be able to have the stats always show. you know when your in the cmd and where it shows what directory your in, i would like it to be right there but in my game. heres the source, i know its cluttered
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <ConsoleColor.h>
using namespace std;
//STAT VARS
int hp=100;
//Login VARS
const string USERNAME = "user";
const string PASSWORD = "123456";
string username, password;
int main()
{
login:
cout<< "================" <<endl;
cout<< "======Login=====" <<endl;
cout<< "================" <<endl;
cout<< "\n Username: ";
cin >> username;
cout<< endl;
cout<< "Enter Password : ";
cin >> password;
cout<< endl;
if(username == USERNAME && password == PASSWORD)
{
system("cls");
cout << green << "CORRECT" <<white<< endl;
Sleep(1000);
system("cls");
goto correct;
}
else
{
system("cls");
cout <<red<< "Invalid login details" <<white<< endl;\
Sleep(1000);
system("cls");
goto login;
}
correct:
char name[20];
cout <<"What do they call you boy?" << endl;
cin.getline(name, 20);
cout << "You should keep moving, " << name << ".Were running out of daylight." << endl;
cout << "\n ***** Press Any Key To Continue *****" << endl;
_getch();
return 0;
}
Remove goto
while ((username != EXPECTED_USERNAME)
&& (password != EXPECTED_PASSWORD))
{
// No need to clear the screen.
cout<< "\n Username: ";
cin >> username;
cout<< endl;
cout<< "Enter Password : ";
cin >> password;
cout<< endl;
}
You should not have your identifiers differ only by case. Although the compiler will treat username different from USERNAME, Good Coding Guidelines state that identifiers (names) should be more different. This is why I used username and EXPECTED_USERNAME in the example above. Something about better readability.
Consistency
You used the std::string type for the username, yet you use char [20] for the boy's name. Be consistent, use std::string for all the types.
Pause for Enter
Trying to detect a keypress without pressing Enter is not as portable as waiting for them to press enter.
Try this:
std::cout << "Press ENTER when ready.\n";
std::cin.ignore(100000, '\n);
Stop Clearing The Screen
Very annoying. There may be information that could be retrieved by scrolling back, but you insist on clearing the screen. Bad form.
Don't Sleep
The input will wait for the User to press the Enter key, so there is no need to sleep. The sleep is not portable.
Also, if you are going to fool people about entering bad passwords, you will need to sleep when they enter a valid password too.
Don't use non-portable console tricks
In modern times, console programs are run in a window; maybe a terminal emulator. The console windows are not standard. Don't rely on colors or clearing the screen or moving the cursor. Display what you need to each time.
If you want to use graphics, develop for a GUI application.
Edit 1: Command Driven Architecture
You will need to have a design or architect following this psuedo code:
While true
{
Input User's text
if User entered quit command, exit program.
else Execute a function based on the Users text
}
This will allow the User to enter the command "stats" at any time.
If you want the User to enter commands while you are displaying text, it is possible, but adds more complication.
The actions of the game should be quick enough that the next command prompt is displayed before the User can enter "stats".
I'm building a product checkout piece of software and I keep hitting a strange bug. I have a central menu that gets user input. After a function is finished with its task, it sends the user back to the menu. For certain functions, however, the cin.get() I have after the menu prompt bugs out and won't accept the first command given. Here are the relevant code fragments:
The main menu loop:
bool foreverLoopFlag = true;
while (foreverLoopFlag) {
cout << "\nC[heckout], R[eturn], S[tudent], P[roduct], Q[uit]. Choice? ";
cin.get(actionChoice);
std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
cout << endl;
actionChoice = toupper(actionChoice);
switch (actionChoice) {
case 'C':
checkoutSoftware(studentMap, productList);
break;
case 'R':
returnSoftware(studentMap, productList);
break;
case 'S':
studentDisplay(studentMap, productList);
break;
case 'P':
productDisplay(studentMap, productList);
break;
case 'Q':
foreverLoopFlag = false;
break;
default:
cout << "Invalid command.\n";
break;
}
}
A problem-child function, studentDisplay:
void studentDisplay(map<string, Student> & studentMap, list<Product> & productList) {
string inputCLID;
cout << "Please enter student CLID: ";
cin >> inputCLID;
if (studentMap.find(inputCLID) != studentMap.end()) {
cout << "\nStudent: " << studentMap[inputCLID].name << " (" << inputCLID << ")\n";
cout << "\tBorrowed items: " << endl;
for (list<Student::LentProduct>::iterator it = studentMap[inputCLID].checkedOut.begin();
it != studentMap[inputCLID].checkedOut.end(); it++) {
cout << "\t\tProduct: " << (*it).name;
cout << "\tDue Date: " << (*it).dateDue << endl;
}
} else {
cout << "\nError: CLID not in database.\n";
}
}
Some of the indention was mangled moving over to SE, I apologize. Here an example of the issue I'm having:
C[heckout], R[eturn], S[tudent], P[roduct], Q[uit]. Choice? s
Please enter student CLID: mrx8394
Student: Mark Xeno (mrx8394)
Borrowed items:
Product: Bluebeard Due Date: 12/14/2013
C[heckout], R[eturn], S[tudent], P[roduct], Q[uit]. Choice? c
Invalid command.
C[heckout], R[eturn], S[tudent], P[roduct], Q[uit]. Choice? q
I tried putting a std::cin.flush() at the beginning of the menu-loop, but that didn't work. I tried doing std::cin.ignore(std::INT_MAX) at the beginning of the menu-loop, but that makes it to where the menu never even shows up. I also tried a std::cin.sync(), but that just makes an infinite cycle of this:
C[heckout], R[eturn], S[tudent], P[roduct], Q[uit]. Choice?
Please enter a product to checkout:
Error: No such product.
I have no idea where to go from here. I know it is probably just some quirk of the iostream that I'm not picking up on. Any assistant would be appreciated.
EDIT: I do not have enough reputation to upvote or comment on specific answers (all of my rep is on Math.SE!!!), so I'll comment here. #Igor-tandetnik 's solution worked perfectly. I had moved everything else over to a getline, but I suppose that guy just got left in the shuffle. My thanks come in droves.
#qwrrty While it may be folly, I had a specification to meet (don't you just love low level University courses). I don't typically ask for help debugging assignments, but this was the last bug and my knowledge of iostream isn't that deep, but I knew someone on here would know what was bugging out my stream state.
Thanks again guys, cheers!
cin >> inputCLID reads characters up to, but not including, the first whitespace character (in your example, a line feed). That character is left in the stream. It is that character that cin.get(actionChoice) later retrieves.
I tend to think that for interactive input, trying to use stdin and/or cin for reading anything other than a full line of input is folly. There are just too many ways for your program to get confused about what's still on the input stream, and end up in an unrecoverable state.
At the very least I'd modify the program to say what command it thinks is invalid, or product that doesn't exist:
default:
cout << "Invalid command '" << actionChoice << "'\n";
and
cout << "Error: No such product '" << productChoice << "'\n";
That way at least you can get an idea of what input the program is actually using for these variables.