Getting stuck in an infinite loop - c++

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

Related

c++ for loop does not terminate

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;
}
}

C++ - fgets() ignores subsequent inputs if Enter is pressed

I am trying to create an emulator for something, and in the main loop for the processor I wanted to implement a simple way to step the CPU one loop at a time (prompted by pressing Enter each loop) so I can see what instructions are being executed each step. In addition, it allows you to enter a number instead of just Enter to change the default step amount from 1 to something else (so it will skip x number of cycles and then return to 1 at a time afterwards.
The issue is that it works fine when I enter a number (skip that amount of cycles and then prompts me again each cycle), but when I just press Enter rather than entering a number I want it to default to 1 step. Instead, pressing Enter causes it to just run through the whole program without ever prompting me again. How do I make Enter == 1?
void CPU_loop()
{
...
static int step = 1;
char cmd[10];
if(step == 1)
{
if(fgets(cmd, 10, stdin) != NULL) // If you entered something other than Enter; doesn't work
{
step = std::atoi(cmd); // Set step amount to whatever you entered
}
}
else
{
--step;
}
...
}
When you press enter directly, it does not default to 1, but instead you are passing the string "\n" to std::atoi(), std::atoi() cannot be used to perform sanity check on it's input, you can use a different function for that like std::strtol() or, you can simply add
if (step == 0)
step = 1;
because when, std::atoi() takes a "\n" as input, it returns 0. Read the documentation to further understand it.
Quoting the documentation
Integer value corresponding to the contents of str on success. If the converted value falls out of range of corresponding return type, the return value is undefined. ​If no conversion can be performed, 0​ is returned.
One more thing, you could do it the c++ way using streams for input to avoid all this.
You could do:
if (fgets(cmd, 10, stdin) != NULL)
{
if (cmd[0] == '\n'){
step = 1;
}
else{
step = std::atoi(cmd); // Set step amount to whatever you entered
}
}

mousePressed within certain region in Processing

I have an background image that I want users to think they're interacting with through Processing. The image has a list of words on it and when the user clicks on the region surrounding the word, I want sound to play and a serial number sent to Arduino.
All that aside, I can't get the mousePressed code right. I'm testing it with println("yikes") right now, and now matter where I click on the screen I get "yikes".
On top of all of that, I'm getting errors on else that I can't figure out. Help appreciated.
void setup() {
size(1475, 995);
// The image file must be in the data folder of the current sketch
// to load successfully
img = loadImage("PaceTaker.jpg"); // Load the image into the program
}
void draw() {
// Displays the image at its actual size at point (0,0)
image(img, 0, 0);
}
void mousePressed() {
if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714);
{
println("yikes");
stroke(0);
}
else println("hello"));
}
Pay close attention to this line:
if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714);
Notice that it ends in a ; semicolon.
This basically says "if the mouse is inside the region, do nothing." Then it gets to the next block of code and always runs it, which is why you're always seeing the "yikes" printed out.
You also have a compilation error on this line:
else println("hello"));
Because it has an extra ) closing parenthesis.
To fix both these problems, get into the habit of always using { } curly brackets with your if and else statements, even if they're just one line, and always check for stray ; semicolons:
if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714) {
println("yikes");
stroke(0);
} else {
println("hello");
}

how to loop in nested if else statement

we are currently creating a mini game for our school project.
the game code is already done but im currently doing some introduction.
i was thinking of putting the mechanics of the game when you run the program and i want to put a menu.
ex.(press 1 to play , press 2 to exit) im already done with the code for the nested if too but i don't know the code for looping it back to asking a number if the user enter a number that's not indicated for example the number 3. I want to loop it back to asking a number until the user input a valid number.
If you are trying to exit the "if" statement, I think you want to use:
continue;
If you are in a switch/case, you would use:
break;
Just create a level.Then if your input doesn't satisfy the conditions ,then jump that level again using goto level and take input again untill it satifies the conditions.
karim:
int a;
cin>>a;
if(a==1){....do what...}
else if(a==2) { ...do what...}
else
goto karim;
Just put all of your actions in a while() cycle and write something like that:
while ((key = getch()) != *exit key*){
if (key == ...){ action 1; }
else if (key == ...){ action 2; }
else if (key == ...){ action 3; }
}

ncurses non-blocking read pushes cursor to bottom of window

My game's main loop relies on a non-blocking read from getnstr. It checks whether the string to which it has read has non-zero length before proceeding with the rest of the loop (I couldn't find the convention for getting this behavior if one exists).
The problem is that it has the effect of forcing the input cursor down the bottom of the window, as if I had spammed Enter or something.
char command[5];
timeout(0);
while (getnstr(command, 4) && gameActive) {
if (strlen(command) == 0) { continue; }
...
}
Agreeing that it seems surprising, but SVr4 curses (which ncurses does match in this detail) always moves to the next row after completing the (attempt to) read characters.
You can see the corresponding code for (Open)Solaris at Illumos's Github in lines 191-207:
/*
* The following code is equivalent to waddch(win, '\n')
* except that it does not do a wclrtoeol.
*/
if (doecho) {
SP->fl_echoit = TRUE;
win->_curx = 0;
if (win->_cury + 1 > win->_bmarg)
(void) wscrl(win, 1);
else
win->_cury++;
win->_sync = savsync;
win->_immed = savimmed;
win->_leave = savleave;
(void) wrefresh(win);
}
that is, the "win->_cury++;" (or the scrolling operation).