It might be quite a simple question, but my following code does not terminate, when I type in s for stop.
for ( roundNr = 1;roundNr <=3; roundNr++) {
optiongame(roundNr);
std::cout<<"Do you want to continue with the game? Press s for stop or press p for play \n";
std::cin>> playstop;
if (playstop == s) {
break;
}
}
Where: Optiongame is some function with different roundNr However, this works fine.
playstop is an input from the user about if he want to continue the optiongame or wants to stop. For that he can press P for play and s for stop
Could anyone help me with that? I would appreciate that
The problem was in if (playstop == s) { I think there is any variable with name s in your code because this there wasn't any error because you are trying to compare variable with variable but you need to change compare variable value to āsā:
try this:
s = 's';
for ( roundNr = 1;roundNr <=3; roundNr++) {
optiongame(roundNr);
std::cout<<"Do you want to continue with the game? Press s for stop or press p for play \n";
std::cin>> playstop;
if (playstop == s) {
break;
}
}
Related
Building a simple GUI in QT. I want to collect a list of strings every time a user inserts a name from the insert button. I got the raw logic to work for cli, however it is not the same when I convert logic to QT/C++ because the program just closes forcefully. I am using lineEdit from the input widgets. What am I doing wrong and what could have been a better alternative?
CLI Logic:
std::cout<<"Enter a name\tor enter nothing to quit"<<std::endl
<<">>>";
getline(std::cin, getNames);
listOfNames[enteredNames] = getNames;
while(getNames.length() > 0){
enteredNames++;
std::cout<<"Enter another name\tor enter nothing to quit"<<std::endl
<<">>>";
getline(std::cin, getNames);
listOfNames[enteredNames] = getNames;
}
QT Logic:
void MainWindow ... buttonClicked(){
v.namesEntered = 0;
v.listOfNames[50]={0};
v.getNames = ui->nameInputBox->text().toStdString();
while(v.getNames.length() > 0){
v.namesEntered++;
v.listOfNames[v.namesEntered] = v.getNames;
}
}
In case you are wondering the dot notations on v data is because I made a structure in mainwindow.h and needed my variables to be global for other functions.
You did not show what v.listOfNames is declared as, but it like a static array, is that right? You should use a std::vector<std::string> instead.
In any case, in your QT code, your while loop runs endlessly if the user enters a non-blank string, since you don't modify v.getNames so that its length() can decrease over time. You probably don't need the while loop at all if the user can enter only 1 string per button click.
Also, you are incrementing namesEntered too soon, and not validating when namesEntered exceeds the bounds of listOfNames if it is indeed a static array.
Try something more like this instead:
CLI
enteredNames = 0;
...
std::cout << "Enter a name\tor enter nothing to quit" << std::endl << ">>>";
while (getline(std::cin, getNames) && !getNames.empty())
{
listOfNames[enteredNames] = getNames;
++enteredNames;
std::cout << "Enter another name\tor enter nothing to quit" << std::endl << ">>>";
}
QT
void MainWindow ... initialize(){
v.namesEntered = 0;
}
void MainWindow ... buttonClicked(){
v.getNames = ui->nameInputBox->text().toStdString();
if (!v.getNames.empty()) {
if (v.namesEntered >= std::size(v.listOfNames)) {
// the list is full, do something else ...
}
else {
v.listOfNames[v.namesEntered] = v.getNames;
v.namesEntered++;
}
}
}
currently I'm having problems with this do ... while loop.
do {
// program code here
cout << "Would you like to run the program again?(yes/no)";
bool exit = false;
string strexit;
do {
getline(cin, strexit);
if (strexit == "no") {
exit = false;
break;
}
else if (strexit == "yes") {
exit = true;
}
else {
cout << "Enter yes to rerun the program, and no to exit.\n";
};
} while (!exit);
system("cls");
} while (exit);
return 0;
}
I researched online, how to break out of do ... while loops, and it's when the condition is true, it loops back again, but if its false it exits.
So if you look at the code, if the user types in no, it sets exit = false, which takes it out of the bigger do while loop, where the break takes it out of the current do while loop.
If the user enters yes, it changes exit to true, which breaks it out of the current do ... while loop, but it doesn't break out of the second.
My question is, (or what I need help with) is that when the user inputs 'no', it cannot exit the do ... while loops, and I'm severely confused as to why. (It loops back to the beginning of the program.)
In the (shortened) code
do
{
bool exit = false;
// ...
} while (!exit);
you actually have two different symbols named exit. Inside the loop you have the variable. Outside of the loop, and used for the condition, you have the function std::exit. Which will be plain exit if you have using namespace std;.
The function exit when used in the condition will decay to a pointer to the function, and it will never be "false". So the condition !exit is always true and you have an infinite loop.
To solve this there are two things you need to do:
Learn that using namespace std; is very bad practice
Move the variable exit to be defined outside the loop. And you should really rename to something more descriptive it as well (the word "exit" is a little bit to general).
I think #SomeProgrammerDude has given excellent advice that's well worth following--but I'd go a step further, and advise moving the code to get the user's response into a separate function so you can more easily reason about each part of the code in isolation:
bool check_for_exit() {
std::string prompt = "\nDo you want to exit the program? ";
std::string strexit;
do {
std::cout << prompt;
std::getline(std::cin, strexit);
prompt = "\nPlease enter yes or no";
} while (strexit != "yes" && strexit != "no");
return strexit == "yes";
}
Then you use that function in the code that does the real work, something on this order:
do {
whatever();
} while (!check_for_exit());
It seems to me that this approach helps avoid many of the problems you encountered in your code.
I have this scanner that works for the two if statements but when it comes to the else statement (if i input random letters it prompts the user with 'please input yes or no') if i input "Yes" it is supposed to run the method real, but instead it just ends the program. How do i get it to take the user input "yes" and then run the method that corresponds with "yes" in the first if statement? i added the for loop to try and fix this problem, and it did, but it also changed the rest of my code to run the real method twice, which is not what i wanted.
public static void scanner() {
System.out.println("Is this a real scenario? Please enter 'Yes' or 'No'.");
Scanner scan = new Scanner(System.in);
String answer;
answer = scan.nextLine();
//for (int x = 0; x < 2; x++ ) {
if (answer.equals("Yes") || answer.equals("yes")) {
real();
} else if (answer.equals("No") || answer.equals("no")) {
hypothetical();
} else {
System.out.println("Please enter 'Yes' or 'No'.");
answer = scan.nextLine();
}
}
}
I had my program running smoothly, and then after commenting it and adding some final touches, it stopped working on me. The function that I am having problems with is using several objects/functions defined elsewhere, so I am just wondering if someone can affirm that my logic is correct and that the infinite loop is not a product of a syntax error. Thanks for your time, here is the problem I'm having:
If the cashier started a new order and wants to close his order, T is typed in. However, when trying to exit an order and loop back to the start of while(moreCustomers), nothing is happening. I am trying to exit the while(moreItems) loop by setting moreItems = false;, but after doing that, it gets stuck in the while(moreItems) loop and does not go back to while(moreCustomers). Does the syntax make sense, and should I be able to break the loop by setting moreItems = false;?
bool moreCustomers = true;
while (moreCustomers)
{
// get input to start new order or close register
drawInstruct("Enter N to start a new order or E to\n close the register.");
char* setFmt = "#"; // the input must be a letter
char input[7]; // char array that stores input from cashier
s.GetStr(xLeftCoord + 1, yTopCoord + 1, input, 1, setFmt, true);
for(int x = 1; x < 10; x++) // clear the input field
{
s.ClearScreenPos(x, 1);
}
if (input[0] == 'N') // if a new order is requested
{
bool moreItems = true;
while (moreItems)
{
getInput(input);
if(input[1]) // if input is not a single char
{
if (input[0] == 'M') // get the desired number of multiples for the current item and update the tape and display area accordingly
{
custTape.handleMultiples(atoi(input)); // adds multiples to tape
curVal = isUPC->price * (atoi(input)); // updates the current item price
drawDisplayArea(curVal); // updates the display area
}
else // invalid number of multiples, prompt for new multiple
{
drawInstruct("Invalid command. Please try again.");
s.Delay();
}
}
else if (input[0] == 'T') // close the order
{
drawInstruct("Order cancelled.");
s.Delay();
moreItems = false; // customer order is complete, exit loop
}
else // invalid command, get new input from the cashier
{
drawInstruct("Invalid command. Please try again.");
s.Delay();
}
}
}
else if (input[0] == 'E') // close the register
{
moreCustomers = false; // no more customers, exit the program
}
else // invalid command, get new input from the cashier
{
drawInstruct("Invalid Command. Please try again.");
s.Delay();
}
}
I can't exit else if(input[0] == 'T'), and any commands I enter in after moreItems = false; work correctly.
I'd set a breakpoint on the first moreItems = false; line to see if it is ever being hit. My guess is that it is not. You've tagged the question with Visual Studio, so if that is what you're using see this link for how to set a breakpoint:
http://msdn.microsoft.com/en-us/library/vstudio/k80ex6de%28v=vs.100%29.aspx
Basically a breakpoint causes your program to stop at that line. Also try setting a breakpoint on this line:
if (input[0] == 'N')
Run the program, press a key, and wait for the breakpoint to be hit. Then use the "Step Over" option on the Debug menu. This runs your program line by line, each time you press "Step Over" (F10 does this too, much quicker). Keep stepping to see what path of execution occurs through your code. You may also be able to hover over variables to see their values.
Theres loads on the net about debugging with visual studio, but if you master the above you'll be well away
So for this assignment I have to include a play again function. Meaning once the person has guessed correctly the program should give the user the choice to play again or not. Also, I am trying to include a function where if the user guesses correctly in 5 guesses or less, then the program should print "Good Job!" and if it takes them more than 5 guesses, it should display "You can do better than that!". Help me please! I am a beginner in programming and I keep getting stuck in trying to fix this problem.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main( void )
{
int i, n = 0, r;
int answer;
srand( time( NULL ) );
r = rand() %100 +1;
char userName[15];
printf("Welcome to GUESS MY NUMBER!\n\nPlease type your name here: ");
scanf("%s", &userName);
printf("\n\nI am thinking of a number between 1 and 100.\n\nCan you guess what it is? ");
while(scanf("%d", &i))
{
if (n >= 9 && i != r)
{
printf("\n\nSorry, the number was %d.\n", r);
printf("You should have gotten it by now.\n");
printf("Better luck next time.\n\n");
system ("PAUSE");
break;
}
if (i > r)
{
n++;
printf("Your guess is high. You only get 10 guesses. Try again: ");
}
else if (i < r)
{
n++;
printf("Your guess is low. You only get 10 guesses. Try again: ");
}
else if (i == r)
{
printf("\n\nCongratulations %s!\nYou guessed the number within %d guesses!\nWould you like to play again? y/n?\n",userName, n+1,answer);
scanf("%d", &answer);
system ("PAUSE");
break;
}
}
return 0;
}
An easy thing to do is create a bool variable (originally set to true) which can be checked in the while statement and updated after the user has been given the option to continue or not. Then just change your breaks into continues and you should be in good shape.
Wrap the whole thing in another loop, and at the end of this outer loop, ask the user if he wants to play again. Either a while() or do-while() loop. If the user says yes, continue looping, otherwise exit the loop.
-Initialize the game
-Load any resources needed (in this case, none)
Begin looping continually
- Handle input
- Think
- Show results
End looping if exited
-Free any resources (in this case, none)
-Exit