CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Threaded View

  1. #1
    Join Date
    Jun 2013
    Location
    Langrood, Iran
    Posts
    7

    Problem With read Function

    Here is My Code:

    Code:
    #include <iostream>
    #include <iomanip>
    #include <string>
    #include <fstream>
    #include <cstdlib>
    using namespace std;
    
    class Student
    {
    public:
    	Student(string name = "", int num = 0, int unit = 0)
    	{
    		setName(name);
    		this->num = num;
    		this->unit = unit;
    	}
    
    	void set(string name = "", int num = 0, int unit = 0)
    	{
    		setName(name);
    		this->num = num;
    		this->unit = unit;
    	}
    
    	void setName(string n)
    	{
    		int len = n.length();
    		len = (len < 15) ? len : 14;
    		n.copy(this->name, len);
    		name[len] = '\0';
    	}
    
    	char * getName()
    	{
    		return name;
    	}
    
    	int getNum()
    	{
    		return num;
    	}
    
    	int getUnit()
    	{
    		return unit;
    	}
    
    private:
    	char name[15];
    	int num, unit;
    };
    
    int main()
    {
    	ofstream o("test.bin", ios::out| ios::binary);
    	ifstream f("test.bin", ios::in| ios::binary);
    	Student s;
    	Student st;
    	Student stu;
    	if(!f || !o)
    	{
    		cerr << "Error!";
    		exit(1);
    	}
    
    	string name;
    	int num, unit;
    
    	for(int i = 0;i < 50;i++)
    	{
    		o.write(reinterpret_cast<const char *>(&s), sizeof(Student));
    	}
    
    	cin >> name >> num >> unit;
    
    	while(num > 0 && num <= 50)
    	{
    		st.set(name, num, unit);
    		o.seekp((st.getNum() - 1) * sizeof(Student));
    		o.write(reinterpret_cast<const char *>(&st), sizeof(Student));
    		cin >> name >> num >> unit;
    	}
    
    	f.read(reinterpret_cast<char *>(&stu), sizeof(Student));
    
    	while(f.good())
    	{
    		if(stu.getNum() != 0 )
    		{
    			cout << "Name : " << stu.getName() << endl;
      		}
    
    		f.read(reinterpret_cast<char *>(&stu), sizeof(Student));
    	}
    
    	f.close();
    
    	return 0;
    }
    My Problem is When I Write n Student's information in file, Read Function only read n - 1 information from file! for example if I enter this input:

    1 1 1
    2 2 2
    -1 -1 -1

    Output is :
    Name : 1
    Last edited by N@R!MAN; July 21st, 2013 at 04:50 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured