Member Avatar for GreenDay2001

I am trying to make this program as my school project.

This program basically gets data from user store it in an object per and then saves it into a file PEARSON.TXT.

Now the problem is that i am not able to write the data into files I dont know why, but when i remove a few lines from it it runs but thats not what i want.

Also I observed that the last loop is also not doing well, i mean not running.

I know there is other ways to do this, but i have adopted this approach because i have to add more functions to that and have planned everything. Its just starting.

// FILE_IO.CPP
// Save the entered data into files and could be later viewed.

#include<fstream.h>
#include<conio.h>
#include<string.h>


class pearson
{
   protected:
     char name[40];
     int age;
   public:
     void showdata();
     void getdata();
     void copydata(pearson);
};

void pearson::showdata()
{
   cout << "\n\n\t\tName: " << name;
   cout << "\n\t\tAge: " << age;

}

void pearson::getdata()
{
   cout << "\n\t\tEnter name: "; cin >> name;
   cout << "\t\tEnter age: "; cin >> age;
}
void pearson::copydata(pearson p)
{
   strcpy(name, p.name);
   age = p.age;
}

void main()
{
    clrscr();

    int s=0,l=0;
    char ch='y';

    pearson per, *per2[100];
    fstream file;


    file.open("PEARSON.TXT", ios::app | ios::in | ios::out);

      file.seekg(0);
      while(!file.eof())
      {
        per2[s] = new pearson;
        file.read((char*)&per, sizeof(per));
        per2[s]->copydata(per);
        per2[s]->showdata();
        s++;
      }
      l=s;



    do
    {
       per.getdata();
       per2[l] = new pearson;
       per2[l]->copydata(per);
       per2[l]->showdata();
      // file.write((char*)&per, sizeof(per));
       cout << "\n\t\tEnter Another: "; cin >> ch;
       l++;
    }
    while(ch!='n');

    cout << "\n\n\t\tAll entries are as follows: ";

    file.seekg(0);

    s=0;

    while(s!=l)
    {
        per.copydata(*per2[s]);
        file.write((char*)&per, sizeof(per));
        s++;
        cout << "\n" << s;
        per2[s]->showdata();
    }
    s=0;
    file.seekg(0);
    while(!file.eof())
    {
       file.read((char*)&per, sizeof(per));
       //per.showdata();
       per2[s]->showdata();
       s++;
    }
    file.close();
    getch();
}

Too many things to say:

1. Don't use void main( ) , its not standard, use int main( ) instead.

2. If you are using C++ why keep old C style headers.

// instead of 
#include <string.h> 
// use
#include <string>
using namespace std ;

The same goes for the other standard C++ headers.

Don't use conio.h its non portable and present only in Turbo C. Use iostream instead for for input and output.

Therefore change your header part to:

#include <iostream>
#inclue <cstring> // for C style strings
#include <fstream>
#include <string> // for the string class

2. The whole reason of using C++ and OOP's is to provide abstraction and an easy interface for invoking core functionality. Instead of delegating all your functionality to the class you have added all the functionality in main itself.

3. Why are you using char[40] when a safe and cleaner options of string is there for you?

4. Why create a static or fixed array of Person objects when you can create Person objects on the fly and store them in C++ vectors.

So in the end I would say that you have really written C using C++. Try thinking about the design on a peice of paper and working all the details out.

Repost if any doubts.

Member Avatar for GreenDay2001

Actually, I doing what my school has taught and in our syllabus. I know its primitive c++ that they are teaching.

1. If you are using C++ why keep old C style headers.

// instead of 
#include <string.h> 
// use
#include <string>
using namespace std ;

what does using namespace std mean. Please tell me. haven't taught about it yet.

Don't use conio.h its non portable and present only in Turbo C. Use iostream instead for for input and output.

I was using conio.h for clrscr() and getch().

Therefore change your header part to:

#include <iostream> // y do i need this, its included in fstream
#inclue <cstring> // for C style strings
#include <fstream>
#include <string> // for the string class

2. The whole reason of using C++ and OOP's is to provide abstraction and an easy interface for invoking core functionality. Instead of delegating all your functionality to the class you have added all the functionality in main itself.

You are damn right....what i was doing now was just scrap. But i think I'll have to modify it right now only.

3. Why are you using char[40] when a safe and cleaner options of string is there for you?

I didnt understood. Whats the other approach.

4. Why create a static or fixed array of Person objects when you can create Person objects on the fly and store them in C++ vectors.

Well, whats c++ vectors.

Conclusion

So whatever i have been taught till now is really primitive, i suppose. So it would be really nice if you could tell me some online resources and good books which may help me.

>what does using namespace std mean. Please tell me. haven't taught about it yet.
In 1998, C++ was standardized. The old headers that end with .h (iostream.h, fstream.h, etc..) were removed and replaced with headers of the same name without the .h extension. Also, a feature called namespaces was added to help with naming conflicts and every name in the standard library was placed in the std namespace. So in standard C++, you would have to do this:

#include <iostream>
#include <string>

int main()
{
  std::string name;

  std::cout<<"What's your name? ";
  std::getline ( std::cin, name );
  std::cout<<"Hello, "<< name <<"!\n";
}

Naturally, that's tedious. Programmers are lazy people and don't want to type std:: everywhere, so two tricks were added to remove that need. The first is a using declaration where you specify each name you're going to use. Just type the keyword 'using' followed by the fully prefixed name and every subsequent use of that name in scope won't require a prefix:

#include <iostream>
#include <string>

int main()
{
  // These are using declarations; one for each name
  using std::string;
  using std::cout;
  using std::getline;
  using std::cin;

  // Now you don't need the prefix, but have to add a
  // using declaration for each new name
  string name;

  cout<<"What's your name? ";
  getline ( cin, name );
  cout<<"Hello, "<< name <<"!\n";
}

If you're even lazier than that, you can create a using directive. A using directive basically creates using declarations for every name in the namespace. You make one by typing the 'using' keyword followed by the 'namespace' keyword and the name of the namespace:

#include <iostream>
#include <string>

int main()
{
  // Declares the use of every name in the std namespace
  using namespace std;

  // Now you don't need the prefix for any standard names
  string name;

  cout<<"What's your name? ";
  getline ( cin, name );
  cout<<"Hello, "<< name <<"!\n";
}

You can use either one you want, but be aware that I put them both inside main. You want to restrict the scope of using declarations or directives as much as possible. In other words, you should avoid this common practice:

#include <iostream>
#include <string>

// Not a good practice at global scope
using namespace std;

int main()
{
  // Now you don't need the prefix for any standard names
  string name;

  cout<<"What's your name? ";
  getline ( cin, name );
  cout<<"Hello, "<< name <<"!\n";
}

That's something that only makes sense when converting old-style C++ to standard C++ with namespaces. Any new code should be written with more care.

>I was using conio.h for clrscr() and getch().
Neither of which you need. getch can be replaced with cin.get() and clrscr() is almost always a superfluous feature that nobody cares about anyway except when it interrupts their flow of work.

>I didnt understood. Whats the other approach.
The other approach is the string class I used in my examples above. Chances are good that you're not allowed to use it in your course, so just remember that it exists and is a better alternative for now.

>Well, whats c++ vectors.
The vector class is more or less a replacement for arrays. It defines a dynamic array that grows and shrinks without you having to worry about how. Once again, this is something you probably aren't allowed to use just yet, but it's a good idea to learn about it on your own. A lot of example code on this forum uses vectors. Also, the vector class is usually an introduction into template container classes.

>So whatever i have been taught till now is really primitive, i suppose.
Not primitive as much as outdated

>So it would be really nice if you could tell me some online resources and good books which may help me.
Accelerated C++ is the best introductory book to standard C++ that I've seen. You can find a collection of documents by Alf Steinbach called Correct C++ as well.

So it would be really nice if you could tell me some online resources and good books which may help me.

If you are using Turbo C and if it is possible for you to use a compiler of your choice, go for either Code:Blocks or any of the good ones... You can find the links in the forum sticky "Starting C".

Atleast by using a good compiler you would be kept away from using compiler specific functions like clrscr( ) and all that.

Member Avatar for GreenDay2001

Thanks Narue and ~sos~.

Well, i use Turbo c++ 3.1.

I also have Visual c++ 6.0. I hope everything will be ok with that.

Whatever, how could I make my program work well, which i have posted. I could not use vectors and string classes right now cause its not in out course right now.

I probably have to use outdated c++, however i will learn standard one, it really seems interesting.

Member Avatar for iamthwee

>Also I observed that the last loop is also not doing well, i mean not running

That may be due to a problem with the way you are reading in your file. Problems with EOF to be exact.

Also, there is no need to be using opening your file in binary mode. So don't.

I'll post up an example to read in files properly if you like.

Member Avatar for GreenDay2001

yes please, i would like an example.

Member Avatar for iamthwee

How does your text file look

Is it

name age
name age
name age

or

name
age
name
age
name
age
Member Avatar for GreenDay2001

My text file isnt really a readable text file. It basically saves the object. So there's a lot of garbage characters. So each entry in that file takes 42bytes(40for name and 2 for int).

Member Avatar for GreenDay2001

something like this

vishesh JÓ€¼ÔêÿÓ€³�–2¼ –òÿñ7– ÔÓvartika JÓ€¼ÔêÿÓ€³�–2¼ –òÿñ7– Ô vishesh JÓ€¼ÔêÿÓ€²�–2¼ –òÿé7– Ô kusum JÓ€¼ÔêÿÓ€³�–2¼ –òÿñ7– Ô

Member Avatar for iamthwee

Ok back to basics, forget classes for the time being.

Let's show you how to read a text file


Reading

#include <fstream.h>
#include <iostream.h>
#include <string.h>
#include <conio.h>
void main()
{
  char line[101]; //or some other arbitary text

  
  ifstream open ( "c:\\yourfile.txt" );
  
  while(open.getline(line,101)) //read in a line
  {
       cout << line << endl;                                         
  } 
  open.close(); //close file
  getch();
}

Writing

#include <fstream.h>
#include <iostream.h>
#include <string.h>
#include <conio.h>


void main()
{
  char line[101] = "write to my file"; //or some other arbitary value

  
  ofstream write ( "c:\\yourfile.txt" );
  
  
       write << line << endl;                                         
  
  write.close(); //close file
  getch();
}
Member Avatar for GreenDay2001

Oh gosh, so you were referring to ifstream and ofstream classes. Well this i know. Right now I am using fstream class for both reading and writing.

I have stored an object into this text file, so I need to read the file and store it back to the object.something like this

fstream file;
file.write((char*)&obj, sizeof(obj));
file.read((char*)&obj, sizeof(obj);
Member Avatar for iamthwee

Hmm, I wouldn't do it like that.

You can get really messed up.

When you read in your file you can just separate the line into two parts i.e the student name and their age.

Then you can place these in your class structure.

So you have a decision.

You can do it your way, where you'll get confused and prolly read in junk.

Or my way. Which is much easier to understand and guaranteed to work.

Member Avatar for GreenDay2001

Oh, yeah nice idea. I would like to work woth that.

But its my school project I will probably have to use the both approach.

Member Avatar for iamthwee

No offence but I can't see how using

file.write((char*)&obj, sizeof(obj));
file.read((char*)&obj, sizeof(obj);

would be easier to understand my proposed way.

So do you want me to show you my way?

I also have Visual c++ 6.0. I hope everything will be ok with that.

:eek: :eek: :eek: That compiler is buggy, very old, not very compiliant with c or c++ standards, and has sever million other problems. Microsoft wrote that compiler to write MS-Windows programs, not to learn how to program. You would be better off with pencil & paper than you will be trying to learn the c++ language with that compiler.

Download the latest Visual C++ .NET Express or get Dev-C++ if you want good modern compilers that recognize most (but not all) c and c++ standards. There are no compilers that are 100% compliant, but those two are pretty close.

Member Avatar for iamthwee

:eek: :eek: :eek: That compiler is buggy, very old, not very compiliant with c or c++ standards, and has sever million other problems. Microsoft wrote that compiler to write MS-Windows programs, not to learn how to program. You would be better off with pencil & paper than you will be trying to learn the c++ language with that compiler.

Download the latest Visual C++ .NET Express or get Dev-C++ if you want good modern compilers that recognize most (but not all) c and c++ standards. There are no compilers that are 100% compliant, but those two are pretty close.

I think he/she should just use turbo C, which is what his/her school expects them to use. Otherwise they'll just get confused.

>file.write((char*)&obj, sizeof(obj));
>file.read((char*)&obj, sizeof(obj);
This is broken. What you're trying to do is convert an object into a sequence of bytes, an operation called punning. However, the rules for punning an object are very strict, and your class doesn't meet the requirements. When you try to pun a non-POD object into an array of char, you're risking all kinds of problems related to undefined behavior.

>void main()
I'll let conio.h slide, iamthwee, but not void main. I don't care if you were thinking of an ancient compiler when you wrote those programs, void main has never been correct C, even as far back as C's predecessor languages.

>That compiler is buggy, very old, not very compiliant with c or c++ standards, and has sever million other problems.
Actually, it's a pretty good compiler for C. The real problems show up when you try to write standard C++.

Member Avatar for iamthwee

void main / int main.

I honestly can't remember what works in turbo c. If it compiles in turbo c without errors I'd be impressed.

>I honestly can't remember what works in turbo c.
int main has always worked. :rolleyes:

Member Avatar for iamthwee

>I honestly can't remember what works in turbo c.
int main has always worked. :rolleyes:

Yeah well, I'm silly and can't remember all the little things that are different in turbo c. If it makes you feel better goofy. :lol:

Member Avatar for GreenDay2001

No offence but I can't see how using

file.write((char*)&obj, sizeof(obj));
file.read((char*)&obj, sizeof(obj);

would be easier to understand my proposed way.

So do you want me to show you my way?

Well, this is my school assignment, so probably i have to do this both way.

:eek: :eek: :eek: That compiler is buggy, very old, not very compiliant with c or c++ standards, and has sever million other problems. Microsoft wrote that compiler to write MS-Windows programs, not to learn how to program. You would be better off with pencil & paper than you will be trying to learn the c++ language with that compiler.

Download the latest Visual C++ .NET Express or get Dev-C++ if you want good modern compilers that recognize most (but not all) c and c++ standards. There are no compilers that are 100% compliant, but those two are pretty close.

Well, what about Visual C++ .NET 2003, my friend has got that. MSVC2005 is quite huge to download. It would take great time plus great money.

I think he/she should just use turbo C, which is what his/her school expects them to use. Otherwise they'll just get confused.

You are really right. However I would also learn the above IDE and compilers to learn up new things and a standard c++.

Member Avatar for iamthwee

>Well, this is my school assignment, so probably i have to do this both way.

LOL silly school.

There is a lot dat can go wrong.

I'd imagine you'd have to use something akin to the following:

http://www.informit.com/guides/content.asp?g=cplusplus&seqNum=129&rl=1

And dat only works on the proviso that the object in question does not have any pointers to dynamically allocated objects of its own i.e. std::string's, std::vector's, etc... Luckily for you, you ain't using STL containers. And let's not even mention composite objects. The logical size of such objects will not be simply sizeof(obj) but something more complicated. And will depend largely on the design of your project.

Frankly, it's a bad idea to use for a newbie -( in my opinion)

Member Avatar for GreenDay2001

LOL silly school.

damn silly, school

And dat only works on the proviso that the object in question does not have any pointers to dynamically allocated objects of its own i.e. std::string's, std::vector's, etc... Luckily for you, you ain't using STL containers. And let's not even mention composite objects. He he.

Frankly, it's a bad idea to use for a newbie -( in my opinion)

So used another new term. Woof, C++ must have been named C**/Cxx after 1998, multiplied not just incremented.

Member Avatar for iamthwee

What I would do is give your teacher the finger and do it my.

But that's just little ol' me. :cheesy:

Well, what about Visual C++ .NET 2003, my friend has got that. MSVC2005 is quite huge to download. It would take great time plus great money.
.

I think you can get it on CD from eBay

If you want to write any MS-Windows programs, then you also need the most recent version of Windows Platform SDK, also free for downloading. I think you can also get it on CD for nominal cost.

Isn't there a distributor in India where you can get those things locally? If not, maybe you and ~S.O.S~ aught to start one and make a billion piles of money :)

Member Avatar for GreenDay2001

Well there are plenty of them. But I won't be able to reach those places. I will have to go with my dad who doesn't have much time. Although I have told him about this, and he may send a man there to get one.

Isn't there a distributor in India where you can get those things locally? If not, maybe you and ~S.O.S~ aught to start one and make a billion piles of money :)

Well, if we start we wont be benefitted much. He lives in Mumbai and I live in Delhi. However we could spread our business in India's largest cities.:)

>>havent you heard of level of piracy in india
no, I don't know a thing about it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.