problems with while statements


HI
every time I try to debug this program in Microsoft Visual C++, I get a pop up that says ---->

"Run-Time Check Failure #3 - The variable 'count' is being used without being initialized."

and it asks if I want to break or continue the program. Can someone please tell me what I'm doing wrong? I get this message in all of my while statements.

Thanks





#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

int main()
{


int count;
int val;

srand (time(NULL));
val = rand() % 100+1;

cout<<"Enter a number between 1 and 100"<<endl;

while (count != val)

{

cin>>count;
if (count < val)
{
cout<<"Try higher"<<endl;
}
else if (count > val)
{
cout<<"Try lower"<<endl;
}


}



cout<<"Congratulations"<<endl;

system("PAUSE");
return 0;
}
Last edited on
you dont initialize the varibale count.
1
2
3
4
5
6
7
int count; //count not initialized
int val; //val not initialized

srand (time(NULL));
val = rand() % 100+1; //val is initialized

while (count != val) ... //count still not initialized 

two solutions:
since val is a random number. initialize count with 0, val-1 or something like this, so count is != val (or else you will not enter the loop)
or
(i would do this), since you will initialize count in your loop via cin, use a do while loop.
Last edited on
Notice that count is the name of a function in the standard library ( http://www.cplusplus.com/reference/algorithm/count/ ), which you bring into the global namespace when you say using namespace std;

It's best that you either avoid using the entire std namespace or change the variable name.
Thanks Mathes,
that solved it
Topic archived. No new replies allowed.