Incremented int is resetting at the end of the function - c++

This is the function in question. The variable in question is count1. Prior to return count1; the function appears to reset count1 to either 1 or 2. The result of the final cout line is n lines where n=number of tries including the correct answer. Each line outputs a number that is 1 higher than the line below until count1 = either 1 or 2. I haven't been able to establish a pattern as to which it will finally output.
The questions themselves are simply placeholders.
What on Earth is going on?
Note: I am a very new programmer, and I am aware that there are likely more efficient ways to do what I am doing that I have not learned. I'm open to suggestions, but my understanding of those suggestions will likely be hampered by my unfamiliarity with C++
int q1(int count1) //q1() is always fed a value of 1.
{
using namespace std;
if (count1 <= 3) //User gets 3 tries to answer for full credit.
{ //count1 is returned in order to determine user score.
cout << "What is 2+2 \n"; //problem appears to occur between here and the end of this if statement.
double a1;
cin >> a1;
if (a1 == 4)
{
cout << "Yup. You know what 2+2 is. \n\n";
}
else
{
wrong(); //wrong() is a single line void function using std::cout and nothing else.
q1(++count1);
}
}
else
{
cout << "You have used all three tries. Next question. \n\n";
++count1; //count1 is incremented for an if statement in int main()
}
cout << count1 << "\n"; //This line is strictly for debugging
return count1;
}
Output of the final cout line looks along the lines of this:
5
4
3
2
Without \n
5432
EDIT:
There was an answer below that is deleted for some reason that appeared to resolve my problem.
The answer stated I should replace q1(++count1) with count1 = q1(++count1);
In my mind this shouldn't work, but in practice it seems to work. Why?

When using recursion, the first time your function runs count1 is 1 (as you said). If the user answers right, then your function will return 1, because the value of count1 never changes.
If the user answers wrong, then count1 increases by 1 and gives it's value to a new function (of the same type). Keep in mind that you pass the value of count1, that means the new function (the second q1()) will get the number 2 but will have a new variable count1. They may have the same name, but they are different variables.
There are two ways to solve your problem:
Either by using pointers, this way you pass the address of count1, and each function changes the same variable. (This is the hardest way and not the most efficient) or
Instead of making recursive calls, you can make a while like so:
int q1(int count1)
{
using namespace std;
while (count1 <= 3) //Run as long as user has chances
{
cout << "What is 2+2 \n";
double a1;
cin >> a1;
if (a1 == 4)
{
cout << "Yup. You know what 2+2 is. \n\n";
//Using `break` you stop the running `while` so the next
//step is for the function to return
break;
}
else
{
wrong();
//By incrementing `count1` the next time the `while` runs
//if user ran out of tries it will not enter the loop, so
//it will return `count1` which would most likely be 4
count1++;
}
}
//Here the function is about to return, so you check if user won or lost
if (count1 == 4)
cout << "You have used all three tries. Next question. \n\n";
//Debug
cout << count1 << "\n";
//Return
return count1;
}

Related

While loop not ending when condition is met

void getPlayerRolls(int RollValues[], int& AttemptCount) {
int i = 0;
int FrameNumber = 0;
int RollNumber = 0;
while(RollValues[i] != -1) {
FrameNumber++;
cout << "Frame # " << FrameNumber << endl;
cout << "Roll #1 "
<< " ";
cin >> RollValues[i];
i++;
cout << "Roll #2 "
<< " ";
cin >> RollValues[i];
i++;
cout << endl;
}
}
My expectation is that when a -1 is entered for one of the roll values that the program terminates. I tried to create a while loop that works with an array but I am having trouble determining how to do this.
I removed lines from your function that are not part of the problem, but maybe this will clarify:
while(RollValues[i] != -1) {
cin >> RollValues[i];
i++;
cin >> RollValues[i];
i++;
i++;
}
What is the value of i by the time the loop condition variable is tested?
The first rollvalue entered is read into some place in the array, but then i is incremented, so if you read back from RollValues[i] you read from a different place in memory! Not only that, you never look at the first roll before accepting the second. And then you increment i yet again. By the time you're back at the top of the loop, i has been advanced 3 times, and neither of the entered rolls is ever tested.
You have other issues too, such as
receiving an array has no "size" information associated, so you do not now how big of an array the caller provided. Your code therefore cannot protect against overruning the memory.
in your while loop, you advance 3 times per iteration, so even if your loop condition checks for boundary cases, you still could have walked off the end of the array before getting back to the top of the loop.
Therefore, I suggest the following:
1) pass in the size of your array into your function, or use a safer data structure, such as std::array or std::vector
2) only process a single roll per loop, and check that you're within bounds before advancing.
3) don't advance your index variable until you're done looking at the value in that place that it refers.

C++ special-value-type loop has to exit when a negative value is entered without using break statement

I just completed a program that has to quit when a negative value is entered as input. Everything is working good except for only one issue, it quits the program after the second time a negative value is entered. After some research I noticed the use of break, however the samples I have to guide the assignment use only if and else statement.
#include <iostream>
using namespace std;
int main()
// insert code here...
// create a variable named "pounds" that can be used to store an integer.
// wait for the user to type in a value and put that value into the variable ounces
{
int poundsTotal;
int ouncesTotal;
while (poundsTotal >= 0)
{
cout << "Enter pounds or a negative number to quit: ";
cin >> poundsTotal;
ouncesTotal = poundsTotal * 16;
cout << poundsTotal << " pouds is " << ouncesTotal << " ounces." <<endl;
cout << " Enter pounds or a negative number to quit ";
cin >> poundsTotal;
poundsTotal++;
}
if (poundsTotal == 0){
cout <<"you enter a zero value" <<"Try onemore time";
}
else {
cout << "you chose to quit the program" <<poundsTotal;
}
}
The condition of a while loop is evaluated after the body has been executed. Then it is determined whether the body will be run again. Change your code and add an if statement inside the loop.
if(poundsTotal < 0) break;
And yes, a break statement is useful in a loop. Otherwise you can't stop the loop before your test condition is evaluated to false.
In your case, I find using a break would be a simple option.
When the program first reaches while (poundsTotal >= 0), poundsTotal has no defined value. This puts you at the mercy of the gods as to whether the program will work as expected or not, and Gods are notoriously unreliable. For more information, look up the term Undefined Behaviour.
The solution to this is ask the user for poundsTotal before the loop and once more at the end of the loop.
If you want to get really posh and do this without repeating code (and stay DRY) , make a function that gets poundsTotal from the user and call this function in the while loop's condition. For example,
while ((poundsTotal = getPoundsTotal()) >= 0)
{
...
}

Why is my while loop function only returning '1'?

Precursor, I just started my first coding class, so forgive me if my mistake(s) is/are painfully obvious. All I need to do right now is use a programmer defined function to ask for an integer and read out an error message until the correct input is entered, then read out the correct input.
#include <iostream>
using namespace std;
bool evenint(int num1_par);//even integer declaration
int main ()
{
int num1, correctnum1;//even integer, function call variable
cout << "Enter an even integer between 2 and 12. \n";
cin >> num1;
correctnum1 = evenint(num1); //function call
cout << "You chose '" << correctnum1 << "'" <<endl;
return 0;
}
/*
Function: evenint
Parameter/Return: An even integer between 2 and 12 inclusively
Description: This function ensures the input matches parameters before
returning its value
*/
bool evenint(int num1_par)
{
if (!(num1_par>=2 && num1_par<=12 && num1_par % 2 ==0))// integer must be
between 2 and 12 inclusively
{
while (!(num1_par>=2 && num1_par<=12 && num1_par % 2 ==0))
{
cout << "Your number is invalid, please try again. \n";
cin >> num1_par;
}
return (num1_par);
}
else
{
return (num1_par);
}
}
I've tried switching my if-else/while loop to just a do-while/everything else I can think of but what I have now is the closest I've gotten. When I enter an invalid integer I get the correct response, but when I enter a valid integer it prints, "You chose '1'" no matter what valid integer I input. I've tried everything I know but now I'm stumped. Any help at all would be great!
Your function returns a bool which is either zero or one. Change it to int and your code will work.

Functions in C++ - The 13 Sone game

I am trying to write a program that requires input validation through functions. The idea behind it is much like the 21 stones only it is with 13 and the computer always wins. The game starts with 13 stones and the computer will always choose 1 on the first turn creating a multiple of 4 scenario. This means if the user takes 3 computer takes 1, user takes 2 computer takes 2 and so on until no stones remain. My problem is I am having a hard time getting my head around functions and how data is called from the parameters within so any help with this would be greatly appreciated!
This is what I have sofar.
#include <iostream>
using namespace std;
//function prototypes
bool validPick(int numStones);
int computerPick(int stones_in_pile, int player2taken);
int playerPick(int stones_in_pile);
int main()
{
int stones_left = 13, P1Taken, P2Taken;
cout << "You have shosen to play the game 13 stones against me, the MIGHTY "
<< "COMPUTER!\nThe object of the game is to take 1, 2 or 3 stones from"
<< " the pile on your turn.\nThe player that removes the last stone "
<< "or stones from the pile wins the game.\nGood Luck... You will need"
<< " it! I NEVER LOOSE!!"
<< endl << endl;
computerPick(stones_left, P2Taken);
playerPick(P1Taken);
validPick(stones_left);
//game logic here -- This is far from done.
stones_left -= P1Taken;
stones_left -= P2Taken;
return 0;
}
/******************************************************************************\
* Validate the picked number 1-3 are only valid numbers to choose from. *
\******************************************************************************/
bool validPick(int numStones)
{
if((numStones < 1) || (numStones >3))
cout << "Invalid Selection. 1-3 is all you can have!";
else
return numStones;
}
/******************************************************************************\
* Computer's function calls. Should start with 1. We always want the computer *
* to win the game. *
\******************************************************************************/
int computerPick(int stones_in_pile, int player2taken)
{
if(player2taken == 0)
stones_in_pile -= 1;
else
{
if(player2taken == 1)
stones_in_pile -= 3;
else
if(player2taken == 2)
stones_in_pile -= 2;
else
stones_in_pile -=1;
}
return stones_in_pile;
}
/******************************************************************************\
* Player's Pick function call goes here. The player goes second *
\******************************************************************************/
int playerPick(int stones_in_pile)
{
cout << "Please choose the ammount of stones. 1-3 only! : ";
cin >> stones_in_pile;
return stones_in_pile;
}
Despite the fact that you should better read a beginners book than trying to understand C++ by asking such questions, I will try to explain what is wrong in your code by an example:
bool validPick(int numStones) {
if((numStones < 1) || (numStones >3))
cout << "Invalid Selection. 1-3 is all you can have!";
else
return numStones;
}
This function is declared to return a bool value. However, if the condition in the if-clause turns out to be true, the function does not return anything, that is a mistake. Second, numStones is an int, so when you return it as a bool it will get converted (from int to bool) which is probably not what you want. Honestly, I didnt even try to understand the logic of your program but a valid version of this function could look like this:
bool validPick(int numStones) {
if((numStones < 1) || (numStones >3)) {
cout << "Invalid Selection. 1-3 is all you can have!";
return false;
}
return true;
}
There are many philosophies with functions that produce values and how those values are passed back.
Functions can pass values back to the caller by either modifying the parameter or by returning a value.
The playerPick function can either modify the passed value (by passing by reference):
void playerPick(int& stones_in_pile)
{
cout << "Please choose the ammount of stones. 1-3 only! : ";
cin >> stones_in_pile;
}
Or by returning a value:
int playerPick(void)
{
// Local variable to temporarily hold a value.
int stones_in_pile = - 1;
cout << "Please choose the ammount of stones. 1-3 only! : ";
cin >> stones_in_pile;
return stones_in_pile;
}
Note that the latter version uses a local, temporary, variable and the compiler will return a copy of the value upon end of the function.
I'm using void in the parameter for emphasis here.

Segmentation Fault during Debugging C++

So, have an assignment where I need to solve the N-Queens* problem using the stack.
*N-Queens problem: you have a chessboard with N rows/columns/queens. You must place each queen so that it cannot attack any of the others on the board.
I created a Queen class just to store the row and column positions for each valid queen placed, and that is working fine. As far as I can tell, all of my sorting and checking logic is also fine. However, either in main or my solve function, I'm getting a Segmentation Fault, but only when I debug. When ran normally, it just exits. My debugger unfortunately doesn't let me go line by line, but I've manually done so and still can't figure this out.
void solve(int k, int N)
{
stack<Queen> queenStack;
if(k == N)
{
while(!queenStack.empty())
{
cout << queenStack.top().rowPos << ", " << queenStack.top().colPos << endl;
queenStack.pop();
}//end while
}//endif
else
{
for (int i = 0;i < N; i++)
{
if (isSafe(k,i))
{
Queen queen(k,i);
queenStack.push(queen);
solve(k++,N);
}//end if
else
{
if(queenStack.empty())
{
break;
}//end if
else
{
queenStack.pop();
k--;
}//end else
}//end else
}//end for
}//end else
}//end void
then my main:
int main()
{
int N = 0;
cout << "Please pick an integer 3 or greater and less than whatever you think won't crash your computer." << endl;
cin >> N;
while (N < 3)
{
cout << "Please pick an integer 3 or greater and less than whatever you think won't crash your computer." <<
endl;
cin >> N;
}//end while
solve(0,N);
return 0;
}//end main
my ifSafe is a bool function that just does checks based on row, which I pass in as an int, and then return the true/false for the loop.
First of all, there's an obvious issue in your code that will immediately lead to a stack overrun. The way you recursively call your solve function:
solve(k++,N);
Will first call solve, and then increment k. So solve(0, N) calls to solve(0, N), which in turn calls to solve(0, N) leading to stack overrun. There's no side effects or any external variables that would affect solve and make it behave differently with the same arguments.
I don't fully understand your solution, so I can't tell you how to fix it, but most likely your intent was for queenStack to be visible across the calls, in which case it would make sense to make it global, or to pass it into the solve by reference.
Now to why it finishes just fine when you run it outside of the debugger. My guess would be that you use some kind of non-windows system (mac or linux) and run it from the terminal. This way the program still crashes, but does not show it in any obvious way. The way to see if it finished successfully is to print $? after executing a program:
a#a-dev:~$ ./crash_me
a#a-dev:~$ echo $?
1
If the program executed normally, the return code should be zero.