Hours have been spent!

I don't care how easy the answer is to this. Why, when the word input has been initialized does it say it hasn't been. Is it out of scope or something else?

#include <iostream>
using namespace std;

int main()
{
int input;
//I'm trying to make it so the user has to guess a number between 1 and 10.
//The correct answer is 5-10 but I want it to loop until the right answer is chosen.
cout << "Type a number between 1 and 10 and hope it's right!" << endl;
cout << "Press ENTER once it's been typed!" << endl;

//It keeps saying that input hasn't been initialized.
for (; input>=5 && input <=10;)
{
cout << "Try a number: " << endl;
cin >> input;

if (input < 5 || input > 10)
cout << "Wrong answer!" << endl;
cout << "Try Again." << endl;

}

cout << "Congradulations!" << endl;

return 0;
}
Try this:

int input = 0;
If you had used a do-while loop. You'd never have come across this problem.

1
2
3
4
5
6
7
8
9
10
int input;

cout << "Type a number between 1 and 10 and hope it's right!" << endl;
cout << "Press ENTER once it's been typed!" << endl;

do
{
    cout << "Try a number:";
    cin >> input;
}while( ( input >= 5 ) && ( input <= 10 ) );
Although I will not argue that, it is true with the “do-while” loop. And since I failed to explain my answer…

...The op needs to know why there was an error and why the loops interact differently on this;

Writing this: int input; just declares the variable and makes it ready to be used. But it still does not hold a value. So for your “for-loop” which compares a value to another. I just cant. Which is why my answer was int input = 0;, which gives it a value to evaluate.
Please read the rules of the forum before posting.

Put your code with the {code}{/code} tags (using [] rather than {} to actually work)
And give your questions appropriate titles, "Help", "Not Working", "Confused" and "Hours wasted" aren't really anything we need to know to help you out, and it's frankly rather annoying seeing an entire forum full of titles like these.

Sorry I can't be of more assistance tonight.
Perhaps its the meaning of the word "initialized" which needs clarification.

Consider this program:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main()
{
    int input;
    cout << "input = " << input << endl;

    return 0;
}

Output:
input = 10377848

Note, if you run this the output will almost certainly be different.

So where did the value 10377848 come from? Well the variable input has not been given any initial value, so the number is just whatever happened to already reside in the memory at that location. If we assign an initial value, then the variable has been initialized.

As a general rule, all variables should be initialised before use. There are cases where it isn't necessary, but it should at least be a deliberate decision by the programmer, rather than an accidental omission of something which is necessary.
Topic archived. No new replies allowed.