We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,886 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

program hangs

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 at line no.61. 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";
        exit(0);
        }
	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;
	}
}
1
Contributor
1
Reply
5 Minutes
Discussion Span
1 Year Ago
Last Updated
2
Views
Rupindersingh
Light Poster
26 posts since Jul 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Someone please move this thread to C++ board, I posted it in here by mistake.

Rupindersingh
Light Poster
26 posts since Jul 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0584 seconds using 2.7MB