Trouble with limiting user's input - while-loop

For the following, Im trying to limit the users input to only Y or y or N or n. Please follow my comments on the codes so I can point out what the problem is. I'm very new to this forum, I have a lot of passion for programming, please help me if anyone can. THANK YOU. The while loop(not the do-while loop) is the part I'm having trouble with. I think maybe I didn't use the != correctly. I haven't anything too advance yet, the class I'm in right now is just introductory level.
cout << "Would you like to use this program again?: ",
cin >> ans;
if(ans =='Y'||ans =='y'||ans =='N'||ans =='n')
break;
else //This is where I'm having problem with.
while (ans != 'Y'||ans != 'y'||ans !='N'||ans !='n')
{
cout << "Please enter Y or y if you like to use the program again and N or n do exit.",
cin >> ans; //If the question is asked and no matter what I input for ans, the while loop never gets exited. Why? Is there something I didn't use right?
}
}while (ans == 'Y'||ans =='y');
return 0;

A better way to handle your logic would be to have a single do loop which continually prompts the user for yes/no input until he gives it:
do {
cout << "Please enter Y or y if you like to use the program again and N or n do exit.",
cin >> ans;
} while (ans != 'Y' || ans != 'y' || ans !='N' || ans !='n');

Related

Priority when 2 keys are pressed at the same time - script for a game

Basically, I want it so that when I have 2 keys pressed together (both A and D, specifically), the last key pressed should have priority, and the key before that should be "suppressed" (no input).
For example: in a game, when you press A, your character moves to the left, and when you press D, he moves to the right.
Pressing those 2 keys together makes the character stop.
Now the thing here is that I don't want the character to stop, I want him to continue to move, based on the last key I pressed, even though I'm holding 2 keys at the same time.
I thought this was going to be a trivial task but I actually got a little overwhelmed after trying to learn how to implement this (I'm a noob, sorry :C ), so I came here looking for some help on how to do this on AHK or any easy to compile scripting language that directly changes the input of a key. I'm not trying to modify or create a game, so a script that remaps those keys is enough!
Autohotkey example, following your "A and D, specifically" question:
for k,v in StrSplit("ad")
Hotkey, % "~$" v,Silveirous
Silveirous:
t:=SubStr(A_PriorHotkey,3)
if GetKeyState(t) and (A_ThisHotkey!=A_PriorHotkey)
Send {%t% up}
return
Documentation:
for k,v in, StrSplit(), Hotkey,,,, "~$", SubStr(), A_Prior/ThisHotkey, if, GetKeyState(), t:=... and ... !=, Send {%t% up}
Edit:
Another solution, made to be working as explained in OP's edit/comment:
#If GetKeyState("d","p")
~a::Send {d up}
~a up::Send {d down}
#If GetKeyState("a","p")
~d::Send {a up}
~d up::Send {a down}
#If
Make sure to mind the difference between #If and if (expression) usage cases.
I'm too late but this could help someone in future :)
Basically you need a variable to keep track of which direction the character faced first and act according to that. A code example could be:
let currentDir = 0;
let maxSpeed = (deltaTime * someConstant);
if (IsKeyDown(KEY_RIGHT) && IsKeyDown(KEY_LEFT))
{
if (currentDir == 1)
speed.x = -maxSpeed;
else if (currentDir == -1)
speed.x = maxSpeed;
}
else if (IsKeyDown(KEY_LEFT))
{
currentDir = -1;
speed.x = -maxSpeed;
}
else if (IsKeyDown(KEY_RIGHT))
{
currentDir = 1;
speed.x = maxSpeed;
}
else
{
speed.x = 0.0f;
currentDir = 0;
}
//And at last player's position would change every frame
player.x += speed.x;
Then when you press left while pressing right the character moves left without stopping and vice versa :)

Trying to check size of some cin statement

I have some simple user input function which reads what the user types, ignoring any enter's and taking the first character it comes across. I am using the cin.ignore statement because this is part of a menu, and I want to replay the menu if they enter none of the given options, but only once. Now I basically want to have an if-statement which is true iff the user entered only one character (he may enter multiple enter's before this character), so I wanted to use something like sizeof or length, but I couldn't quite get it to work. Can anybody help with this? It would be much appreciated. Also, if anything should be changed about the phrasing of the question, please let me know. Thanks in advance.
char Interface::leesin ( ) {
char invoer;
do {
invoer = cin.get();
} while (invoer == '\n');
cin.ignore(MAX,'\n');
return invoer;
}
the following is a code snippet whereby the user will be presented with a console menu and needs to input a character. The cin will read in only 1 char and then the program can do some processing with this char. The loop will terminate, when the user inputs the char '9'.
#include <iostream>
using namespace std;
int main() {
char ch;
do {
//print menu here
cin >> ch; // take in one char only
//perform action based on ch
} while (ch != '9');
return 0;
}

Letters stored as integers

#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Please enter an integer between 1 and 5" << endl;
int x; //Selection of menu prompt
cin >> x;
while (x < 1 || x > 5) //Tossing out garbage input
{
cout << "Invalid selection, please make another." << endl;
cin >> x;
}
return 0;
}
When this is run, entering "a" for example, enters the while loop, but does not wait for user input at "cin >> x;" and instead loops infinitely through. Can someone explain to me why this happens and how I might fix the issue? I can only imagine it is something to do with the keyboard buffer.
In this code, it's possible for cin to enter an error state. If the user does not enter an integer, it will fail.
That is, if the user enters a, then cin >> x does not set x, and future calls to cin >> x do not block. You see an endless loop.
You can check for this failure status and clear it. before continuing using code similar to:
if (cin.fail())
{
cin.clear();
cin.ignore();
cerr << "Invalid selection, please make another." << endl;
}
You really should use cin.clear() and cin.ignore() after accepting the input.
cin.clear() clears the error flag on cin, and then cin.ignore(5000, '\n') skips to the next newline. It will skip up to 5000 characters, so the code is assuming the user will not put in a very long.

how interrupt c++ run without typing neither CTRL-C nor introducing cin or system-pause?

I need to do very long simulation, let's say this:
int i;
vector result;
while(true)
{
i = random(8);
if (i < 4) {result.push_back(i);}
}
cout << result;
Is there a way to stop this while loop from console doing something (e.g. pressing a key) without typing CTRL-C or without introducing a cin or system-pause function?
I'd like to let this while loop going on until I decide to stop it!

How to run two loops at the same time?

I have been developing a very simple text game using Objective C and Xcode. It is almost done but I am having a problem, the scanf method stops the loop and asks for user input while I need the computer to be running the rest of the loop, the solution I came up with was running two while loops at the same time, one being the logic loop and another being a loop for user input.
I have been doing my research and it looks like using threads are the way to go, I just have not found a tutorial that will break it down for a n00b in Objective C (I am decent in java, I just have never worked with threads). If anybody could explain them or link me to a very broken down tutorial that would be great. Or if anybody has another idea I am open to anything else.
Necessary Code (The scanf I am having a problem with has asterisks on the line):
while(running != 0)
{
if(gameState == 1)
{
if(timeToGenerateNum == true)
{
while(randNumber < 10000000)
{
randNumber = arc4random() % 100000000;
}
NSLog(#"%i", randNumber);
timeToGenerateNum = false;
}
else
{
while(time <= 2500)
{
NSLog(#"Testing");
time++;
******************scanf("%i", &userNum);************************
if(userNum == randNumber)
{
score += time;
time = 0;
timeToGenerateNum = true;
}
}
NSLog(#"Game Over! Your score was %i!", score);
running = 0;
}
}
else if(gameState == 2)
{
NSLog(#"To play, simply type in the number that appears on the screen.");
NSLog(#"But be careful, you only have a short amount of time before GAME OVER!");
NSLog(#"The quicker you type in the number the more score you get!");
NSLog(#"Are you ready to start, if so type '1' and press enter!");
scanf("%i", &gameState);
}
}
You're going to have to learn a bit about BSD (Unix, Linux) input/output to pull this off: replace your call to scanf with a non-blocking function you write to acquire input from the user's keyboard.
This function should immediately return whatever the user typed, or immediately return with a zero character count if she didn't type anything.
Read up on the select(2) system call, and keep in mind that keyboard input (standard input) is the first file descriptor, file descriptor zero.