By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,950 Members | 1,019 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,950 IT Pros & Developers. It's quick & easy.

Loop Issues

Kindle Life 123
P: 7
My loop keeps on repeating inspite of typing N=1.

here is the code..

void club::enterdata() {
std::cout<<"Enter details";
std::cin>>mno>>memname>>activity;

this is the function... and this is the funcion in which this function is called..

void club::writeinto()
{
club c{};
int N, i = 0;
std::ofstream fout( "project.dat", std::ios::binary );
if( ! fout )
{
std::cout<<"Error";
}
while(!fout.eof())
{
std::cout << "Enter the number of records to be entered";
std::cin >> N;
for(i=0;i<=N;i++) {
c.enterdata();
}
fout.write( (char*)&c, sizeof(c) );
}
fout.close();
}

here is the output..

Enter the number of records to be entered 1
Enter details 12 hka abc
Enter details

Pls help me out..
Sep 28 '18 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
On the first of the loop i is 0 and N is 1, therefore i<= N is true.

Therefore, enter the loop.


Now i is 1 and N is 1, therefore i<=N is true.


Therefore, enter the loop.


Now i is 2 and N is 1, therefore i<=N is false.


Therefore, exit the loop.


Avoid the extra loop cycle by using i != N rather than i <= N.


BTW: c.enterdata() inside club::writeinto() won't compile. The address of the current object is kept in the this pointer. To use the current object inside a member function you code:


this->enterdata();
Sep 28 '18 #2

Post your reply

Sign in to post your reply or Sign up for a free account.