Loop Issues

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kindle Life 123
    New Member
    • May 2018
    • 7

    Loop Issues

    My loop keeps on repeating inspite of typing N=1.

    here is the code..

    void club::enterdata () {
    std::cout<<"Ent er details";
    std::cin>>mno>> memname>>activi ty;

    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.da t", std::ios::binar y );
    if( ! fout )
    {
    std::cout<<"Err or";
    }
    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..
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    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();

    Comment

    Working...