On Tue, 04 Jan 2005 05:44:06 -0500, "beginner10"
<pe************@yahoo.com> wrote:
I'm so out of this! This got 23 errors. Can you help me more?
<snip>
If what you posted here was what you tried to compile, no wonder you got
so many errors--that was an incomplete program.
Assuming that your difficulty was in understanding the comments I made
about your original code, let's try again and start with the basics. If
I am incorrect in my assumption, post back with a better-defined
question.
If I understood your original post correctly, we need to:
Accept up to n person_list records from the user
Write these records to a data file
The first part, getting the user input, is outlined here. Note that
this is NOT complete code.
size_t i, num;
/* Collect data from user (up to MAX_PERSON_LIST entries) */
for (i = num = 0; i < MAX_PERSON_LIST; i++, num++)
{
/* If empty input, terminate data entry */
if (get_input("First name", person_list[i].firstname,
FNAME_LEN)) == NULL)
break;
get_input("Last name", person_list[i].lastname, LNAME_LEN);
get_input("Phone number", person_list[i].phonenumber,
PHONENUM_LEN);
}
Ignore get_input() for the moment. Let's just say that it is a black
box that accepts and validates user input, and returns NULL if an
invalid value is entered.
The loop provides for up to MAX_PERSON_LIST records in the person_list[]
array. The user can terminate entry of records by providing an empty
input for the first name field. You can see that this means we do not
have to know how many records WILL BE created beforehand--we just know
the MAXIMUM we will permit.
Note that 'num' is used to keep track of the number of actual
person_list[] records created.
The second part, writing the records out to a data file, simply requires
another loop:
data_file = fopen(list, "w");
/* ... */
for (i = 0; i < num; i++)
{
fprintf(data_file, "%s %s %s\n", person_list[i].firstname,
person_list[i].lastname, person_list[i].phonenumber);
}
fclose(data_file);
We already know we have 'num' user-entered records in person_list[].
Here, we simply loop through them and write each record to the data file
in turn.
What I've posted here is the lion's share of what is required for this
exercise. What is left to you is the input routine, get_input(), and
additional error-checking.
Hints:
======
get_input() should work with strings. Any data conversion that is
required or desired should be done AFTER obtaining the data from the
user as a string.
An example prototype for get_input() might be
char *get_input(const char *prompt, char *buf, size_t buflen);
Use fgets() instead of scanf() to obtain user input.
Either terminate your output with newlines, or explicitly flush the
output stream. Your original code was replete with "unflushed" prompts
and such.
--
Robert B. Clark (email ROT13'ed)
Visit ClarkWehyr Enterprises On-Line at
http://www.3clarks.com/ClarkWehyr/