By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,050 Members | 1,295 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,050 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";

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 << "Enter the number of records to be entered";
std::cin >> N;
for(i=0;i<=N;i++) {
fout.write( (char*)&c, sizeof(c) );

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

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:

Sep 28 '18 #2

Post your reply

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