2
votes

The following code is supposed to read records from input and store them in a file called file.dat. Then it is supposed to arrange these records in ascending order, but for some reason the program hangs in the second while loop at line "file1.seekg(-(sizeof(r)),std::ios::cur);". Can someone please tell me what's wrong?

#include <iostream>
#include <fstream>
#include <strstream>

int main()
{
std::ofstream file;
file.open("file.dat",std::ios::trunc|std::ios::binary);
if(!file)
    std::cout<<"unable to open for output";

struct record
{
    char code[6];
    char name[20];
    int i;
};

record r;
int a = 0;

while(1)
{
    std::cout<<"Record " << a + 1 << std::endl;
    std::cout<<"Enter character code, name and an int \n";
    std::cin.ignore();
    std::cin.getline(r.code,6);
    std::cin.getline(r.name,20);
    std::cin>>r.i;
    file.write((char *)&r,sizeof(r));
    std::cout<<"\nAdd another (y\\n) : ";
    char c;
    std::cin>>c;
    if(c == 'n')
        break;
    a++;
    std::cout<<'\n'<<'\n';
}
file.close();

std::fstream file1("file.dat",std::ios::in|std::ios::out|std::ios::binary);
if(!file1)
    std::cout<<"unable to open file1";

else
{
    if(a>0)
    {   while(a)
        {
            file1.seekp(0);
            for(int i = a; i>0;i--)
            {
                record r1;
                file1.read((char *)&r,sizeof(r));
                file1.read((char *)&r1,sizeof(r1));
                if(r1.i < r.i)
                {
                    file1.seekp(-(sizeof(r)*2),std::ios::cur);
                    file1.write((char *)&r1,sizeof(r));
                    file1.write((char *)&r,sizeof(r));
                    file1.seekg(-(sizeof(r)),std::ios::cur);
                }
            }

            a--;
        }
    }
    file1.close();
}

std::ifstream file2("file.dat",std::ios::binary);
if(!file2)
    std::cout<<"unable to open file2";
  else
while(1)
{
    std::cout<<"\n\n";
    file2.read((char *)&r,sizeof(r));
    if(file2.eof())
        break;
    std::cout<<r.code<<'\t'<<r.name<<'\t'<<r.i;
}
}
2
Do you know where it hangs? This information would be helpful. Additionally you could try to minimize the example code size. - heinrich5991
Use a debugger and step through the code; that's what it's for... - trojanfoe
std::get.ignore what is that? - Jesse Good
@jesse: its to ignore the newline entered - Rohit Vipin Mathews
@Rohit: Oh, did he mean std::cin.ignore();? - Jesse Good

2 Answers

2
votes

first

change std::get.ignore -> std::cin.ignore()

if you want to discard one character.

it compiled well and created file.dat file..

you might check the record inside file.dat though

2
votes

If you are trying to ignore the new line character entered after the actual dat, then you have to use:

std::cin.ignore();

If you want more reference on use of ignore go to this LINK