1

I am in high school and it is mandatory to use Turbo C++ compiler, I know it is a very old compiler but please understand my situation.

So I was writing a code on a employee database. The code snippet:

userdb user;
fstream fil;
while(fil.read((char*)&user,sizeof(userdb)))
   {
       cout<<user.name;
       cout<<user.pass;
       cout<<user.age;
       cout<<user.address;
   }
fil.close();

Now the problem is that if a user doesn't have his address inputted in the database, the compiler displays garbage.

How can I check if a value has nothing(garbage) so as to not print it on the screen? (I have tried address[0]='\0' and strcmp("",address)==0 and this is not working)

Ishan Sharma
  • 6,545
  • 3
  • 16
  • 21
  • 1
    Still, find a way to be up with the current trend. – Mark Garcia Dec 12 '12 at 07:25
  • Yeah, I use visual studio usually but its a school project and it has to be done on TC. So no choice. – Ishan Sharma Dec 12 '12 at 07:30
  • 1
    The data is read exactly as it is in the file. If the file contain garbage it's nothing you can do when reading it. Instead you should make sure to not write garbage to the file in the first place. Also, if the `userdb` structure uses pointers for the strings, it will never work as pointers can't be stored "as is". – Some programmer dude Dec 12 '12 at 07:31
  • Thanks Joachim. This solves my problem. I just initialize all other fields while creating the file. – Ishan Sharma Dec 12 '12 at 07:46

1 Answers1

2

Empty field does not mean anything in this context. Indeed, you are reading N bytes from a file, storing them into memory. You tell the computer to interpret this portion of memory as a string. There's nothing to be done to know whether the field is empty or not.

Your best bet, would be to look at this memory, and to try to guess whether is looks like an actual address or not.

Maybe first could you look at whether this address string, stored into a character array of a fixed size, has a termination character in it. If not, you could guess that it is invalid, and possibly add this termination character at the end of the character array.

Didier Trosset
  • 36,376
  • 13
  • 83
  • 122