Hi, I am trying to teach myself C++ and its not going as well as I had hoped. This program is supposed to repeat when the user wants it to. In Pascal I used to just use the REPEAT UNTIL loop, but c++ doesn't have that.
On the first pass the program runs fine, then, when the user decides to repeat it just goes haywire, flickering text ect. Is there something obvious I am doing wrong?
In main, you create a variable called repeat. In the while loop, you are checking if that one is bigger than 0. Which it is not because you never initialized it and it has a garbage value.
What you want to do is call repeatfunc and let it decide. You can do this in 2 ways.
1. Create the repeat variable in main and pass it as reference to the function.
2. Create the repeat variable in the function itself and return it to main.
Another problem in the function. You're checking if repeat is equal to 'y'. It will never be equal to 'y', because repeat is an integer, 'y' is not an integer.
Hopefully this will give you a decent idea of the problem =)
though I suspect there is a smarter more efficient way.
Yes, your solution is highly unrecommended. Don't fall back to global variables because it is "easier" in this situation, take your time and do it the proper way, like one of the two ways I suggested.
Yes, your solution is highly unrecommended. Don't fall back to global variables because it is "easier" in this situation, take your time and do it the proper way, like one of the two ways I suggested.
The thing is, I don't have any handbooks or teachers and most of the examples given are a bit to complex for me to figure out exactly what was done and more importantly why it was done. Thanks for your help in any case. I will try and figure it out :)
The only way I could loop the program successfully without using a global variable was to remove the repeatfunc function. I would realy appreciate a simple example of Creating a variable in a function itself and return it to main.
#include <iostream>
usingnamespace std;
int repeatFunction()
{
int repeat;
cout << "Wanna repeat? Enter 1 for Yes and 0 for No: ";
cin >> repeat;
return repeat;
}
int main()
{
int repeat = repeatFunction(); // call the function and save the return in this variable repeat
if (repeat == 1)
{
cout << "Looks like you wanna repeat, wise choice" << endl;
}
else
{
cout << "Poor choice soldiers, now prepare to die" << endl;
}
return(0);
}