First to tell you my issue:
I have written a program that based on this struct..
typedef struct{
char firstname [40];
char lastname [40];
char address [100];
char phone[11];
}contact;
will ask the user for input and then write it to a file. Except that when I do write to the file, it writes i.e for first name, the rest of the 40 characters and so everything is spaced out..
A colleague of mine suggest creating a structure of pointers but I’m unfamiliar with this concept completely. I have this so far in replacement of the above structure:
typedef struct{
char* firstname;
char lastname [40];
char address [100];
char phone[11];
}contact;
in which case I’m only working on first name right now. I have seen examples that create a separate array
char comm[100];
fgets(entry.firstname, 40, stdin);
entry.firstname = new char[strlen(comm)];
or something to this affect but this is giving me fits. What I want is to have the person enter an entry in and the size of the field grow and shrink to what is entered by the user. Any fixes would be appreciated!
Sorry for leaving this out :/ :
pFile = fopen("C:\\contacts.txt", "r+");
if(!pFile){
puts("File could not be open.");
return 1;
}
fwrite(&entry,1,sizeof(entry),pFile);
The problem is that you’re just dumping the entire
contactstructure to a file. What you want to do instead is write out only the characters the user entered. Fortunately, this is easy. To get started, let’s just print out the first name:If you’re using C++, you should use
std::stringinstead of character arrays. Your struct can now look likeAnd you can write to a file using fstream