Just completed the following code - a personal variation on the 'don't press 5' exercise, anyway - it had trouble compiling but still went through - here is the code followed by the compiler output. Could somebody help with interpretation please.
// Ten random numbers between 1 and 100
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <limits>
usingnamespace std;
int main ()
{
int random_numb;
int choice_array[10];
int ran_array[10];
srand((unsigned)time(0));
for (int how_many = 0; how_many < 10; how_many++) // to generate 10 passes through
{
random_numb =rand()% 100 + 1; //placing 10 random numbers into an array
ran_array [how_many] = random_numb;
}
for (how_many = 0; how_many < 10; how_many++)
{
while ((cout << "Pick a number between 1 and 100, any except " << ran_array [how_many] << ":\t") && (!(cin >> choice_array [how_many])))
{
cin.clear(); //clear stream and check for 'wrong input
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if (choice_array[how_many] == ran_array[how_many])
{
cout << "I told you NOT TO GO THERE...and again:- \n";
how_many--;
}
}
cout << "WOW, You really are very patient and follow the rules - BORING!" << endl;
return 0;
Here is the g++ compiler warnings:
line 26: warning: name lookup of ‘how_many’ changed for ISO ‘for’ scoping
line 20: warning: using obsolete binding at ‘how_many’
how_many (line 18) is only in scope from line 18 to line 22. When the loop exits, how_many doesn't exist any more (i.e. it is not in scope) so you can't use it again. You need to redeclare it, change line 24 to for (int how_many = 0; how_many < 10; how_many++)
and then you can use it in the second loop.
how_many only exists in the first for loop you created. After that how_many no longer exists. You'd have to re-create it or create it outside of the first for loop.