Click here to Skip to main content
15,913,246 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My loop keeps on repeating inspite of typing N=1.

here is the code..
C++
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..
C++
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..

What I have tried:

Tried to change the position of the brackets...
Posted
Updated 28-Sep-18 6:21am
v2
Comments
jeron1 28-Sep-18 11:44am    
Is it possible to use a debugger and set a breakpoint in your code and step through each line to see the values of i and N? You could also I suppose, cout the value of N and i in some places to see their value change, or to see which portions of code are being executed.
Richard Deeming 3-Oct-18 15:34pm    
for(i = 0; i <= N; i++)

If N is 1, how many times do you think that loop will execute?

Why do you have this : "while(!fout.eof())" ?

I think that is your problem. There is NO reason to do that. I have been working with C and C++ for thirty years and I have never checked for EOF on an output file while writing to it. EVER. I can't think of any reason to, only reasons NOT to.
 
Share this answer
 
Comments
Member 14001096 28-Sep-18 14:30pm    
As a part of school project, this "while(!fout.eof) is mandatory..
You should learn to use the debugger, you would have seen your mistake in the first run. Reading the documentation is also helping.

Your for loop has the problem that always the C is overwritten before written to the file.
C++
for(i=0;i<=N;i++)
{
    c.enterdata();
    fout.write( (char*)&c, sizeof(c) );
}  
tip: make more detailed I/O for each member in enterdata() and write the data as csv text in the file, so you can better check and reload it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900