boolean flag !!

Hi,please tell me whats the purpose of bool flag given in following code as I am not able to understand being new to C++.

void display_sp(int n)
{
student st;
ifstream inFile;
inFile.open("student.dat",ios::binary);
if(!inFile)
{
cout<<"File could not be open !! Press any Key...";
cin.ignore();
cin.get();
return;
}
bool flag = false;
while(inFile.read(reinterpret_cast<char *> (&st), sizeof(student)))
{
if(st.retrollno() == n)
{
st.showdata();
flag=true;
}
}
inFile.close();
if(flag == false)
cout<<"\n\nrecord not exist";
cin.ignore();
cin.get();
}
Looks like the code is reading data from the data file and storing into the student class (by means of casting the data as a string first).

It looks like it's checking the roll number of the student to see if it matches the argument passed into the function. If it does, it prints the student data. If it doesn't, it prints that the required student doesn't exist.

In this case, the only reason the flag is being used is to print to error message at the end. You could bin it completely by simply closing the file stream and returning right after printing the student data.
Thanks....i also wanna know that whats the meaning of "flag = true;" written after "st.showdata();"....what does it mean....what will happened if dont write it ?
run it and find out?
It's setting the flag to true, a non-zero value.

Why don't you try removing that line and see what happens?

Edit: Starting to think I may have been suckered into answering a homework question here...
Last edited on
flag is a variable, just like any other. Its type is bool. bool variables can take two values: true or false.

The line flag = true; is simply setting the value of the variable to true.

If you look a few lines down, you can see that there is an if statement, that checks the value of flag and outputs some text to stdout if the value is false. If we didn't set the value to true above, it would always output that message, even if the record did exist.
Last edited on
ok...that explains everything....thanks
MikeyBoy and iHutch
.
Topic archived. No new replies allowed.