473,382 Members | 1,689 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

Showing problem


How can i changhe this code showing how many persons i saved to the file?
And it prints pretty much rubbish. Where is the problem?

#include <stdio.h>
int main()
{
int i;
FILE *data_file;
char list[] = "list.txt";

struct person {
char firstname[20];
char lastname[25];
int phonenumber;

};

struct person person_list[50];

for(i=0; i<1; i++) {

printf("Give your firstname:");
scanf("%s", person_list[i].firstname);

printf("Give your lastname:");
scanf("%s", person_list[i].lastname);

printf("Give your phone number:");
scanf("%d", &person_list[i].phonenumber);

}

if ((data_file = fopen(list, "w")) == NULL) {
printf("Error opening file");
return 0;
} else {

for(i=0; i<=2; i++)
{
fprintf(data_file, "%s %s %d\n", person_list[i].firstname,
person_list[i].lastname, person_list[i].phonenumber);
}
}
fclose(data_file);
printf("Data saved succesfully!");
return 0;
}
Nov 14 '05 #1
14 1787
The problem is with your design itself. You declared an array of 50
like
struct person person_list[50]; but in the following statement you are looping for only one person's
input:
for(i=0; i<1; i++) {

printf("Give your firstname:");
scanf("%s", person_list[i].firstname);

printf("Give your lastname:");
scanf("%s", person_list[i].lastname);

printf("Give your phone number:");
scanf("%d", &person_list[i].phonenumber);

}
For printing to the file you are printing for two persons likefor(i=0; i<=2; i++)
{
fprintf(data_file, "%s %s %d\n", person_list[i].firstname,
person_list[i].lastname, person_list[i].phonenumber);
}
}


The solution is
1) Get input for as many persons you want but lesser than the array
length.
2) write the data to the file,.
3) For the above two steps you have to change the for loop to
accomodate the array length.
4) Read the file back and check for the number of lines before you
encounter EOF.

-Shan

Nov 14 '05 #2
beginner10 <pe************@yahoo.com> wrote:
How can i changhe this code showing how many persons i saved to the file?
And it prints pretty much rubbish. Where is the problem? #include <stdio.h>
int main()
int main( void )
{
int i;
FILE *data_file;
char list[] = "list.txt";

struct person {
char firstname[20];
Using 'magic' numbers like this is problematic. Better use a define at
the start of the program like

#define MAX_FIRST_NAME_LENGTH 20

and stick with that, so you only need to change it in a single place
when you later realize that 19 characters isn't enough to store all
first names.
char lastname[25];
int phonenumber; };

struct person person_list[50];
Again, I would recommend to use

#define MAX_PERSONS 50

instead of a fixed number.

for(i=0; i<1; i++) {
Why would you stop here once 'i' is 1? Wouldn't it make more sense
to bail out of the loop if 'i' is 50 or the user enters something
from which you can deduce that (s)he doesn't want to enter more data
(like an empty line for the first name)?
printf("Give your firstname:");
scanf("%s", person_list[i].firstname);
Let's hope there's no-one with a space in the name, otherwise using
scanf() like that won't work (hint: scanf() stops at white-space
characters when reading in strings with "%s"). And moreover, better
hope that there's no-one with a first name that's longer than 19
characters or you write past the end of the array. As a way to
correct both problems look up the fgets() function.
printf("Give your lastname:");
scanf("%s", person_list[i].lastname); printf("Give your phone number:");
scanf("%d", &person_list[i].phonenumber);
Using scanf() here is is going to be a problem if the user makes a
typo and enters an non-digit (maybe just a space). Again, look up
fgets() and check the buffer you get from it for something that can
be interpreted as a phone number.
}

if ((data_file = fopen(list, "w")) == NULL) {
printf("Error opening file");
return 0;
} else {
Actually, no 'else' is needed here - when opening the file failed you
already exited the program.
for(i=0; i<=2; i++)
Since you stop above when 'i' is 1 you never have more than a single
person in your list, Why would you try to write out now 3 sets of
data records? Better keep count how many people got entered by the
user and than write out as many records.
{
fprintf(data_file, "%s %s %d\n", person_list[i].firstname,
person_list[i].lastname, person_list[i].phonenumber);
}
}
fclose(data_file);
printf("Data saved succesfully!");
return 0;
}

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #3
Neo

"beginner10" <pe************@yahoo.com> wrote in message
news:d9******************************@localhost.ta lkaboutprogramming.com...

How can i changhe this code showing how many persons i saved to the file?
And it prints pretty much rubbish. Where is the problem?

#include <stdio.h>
int main()
{
int i;
FILE *data_file;
char list[] = "list.txt";

struct person {
char firstname[20];
char lastname[25];
int phonenumber;
better to use char array for phonenumber field too....
lets say user input something like : 9899325025
then it will overflow and store wrong information.
by using char array you have more precise control
over how many digits you want to store in phonenumber
field.


};

struct person person_list[50];
Oops! use #defines instead of magic numbers....
like #define MAX_RECORDS 50

for(i=0; i<1; i++) {

printf("Give your firstname:");
scanf("%s", person_list[i].firstname);

printf("Give your lastname:");
scanf("%s", person_list[i].lastname);

printf("Give your phone number:");
scanf("%d", &person_list[i].phonenumber);

}

if ((data_file = fopen(list, "w")) == NULL) {
printf("Error opening file");
return 0;
} else {

for(i=0; i<=2; i++)
{
you have valid data only in first record, but here you are accessing
and storing second and third row also... that contains garbage.
either properly initialize the whole array in the begining of the program
if you want to store more records then input from the user.
or better keep this loop counter same as above.

Hope this will help U....

-Neo
fprintf(data_file, "%s %s %d\n", person_list[i].firstname,
person_list[i].lastname, person_list[i].phonenumber);
}
}
fclose(data_file);
printf("Data saved succesfully!");
return 0;
}

Nov 14 '05 #4
I'm still doesn't understood this? Sorry.

Nov 14 '05 #5
I'm still doesn't understood this? Sorry.

Nov 14 '05 #6

"beginner10" <pe************@yahoo.com> wrote in message
news:56******************************@localhost.ta lkaboutprogramming.com...
I'm still doesn't understood this? Sorry.


I think he means that if you have 25 persons, they will probably have 25
phonenumbers, too.
Nov 14 '05 #7

"beginner10" <pe************@yahoo.com> wrote in message
news:88******************************@localhost.ta lkaboutprogramming.com...
I'm still doesn't understood this? Sorry.
Please don't drop attributions and context. See below.

"Neo" <ti***************@yahoo.com> wrote in message
news:33*************@individual.net...
"beginner10" <pe************@yahoo.com> wrote in message

news:d9******************************@localhost.ta lkaboutprogramming.com...

How can i changhe this code showing how many persons i saved to the file? And it prints pretty much rubbish. Where is the problem?

#include <stdio.h>
int main()
{
int i;
FILE *data_file;
char list[] = "list.txt";

struct person {
char firstname[20];
char lastname[25];
int phonenumber;


better to use char array for phonenumber field too....
lets say user input something like : 9899325025
then it will overflow and store wrong information.
by using char array you have more precise control
over how many digits you want to store in phonenumber
field.


What he means is that you're only guaranteed (by the
language standard) a range of values for type 'int' from
-32767 to 32767 inclusive. Attempts to store a value outside
the range of a signed integer type will produce undefined
behavior.

Of course many implementations provide a type 'int' with
a much larger range, but you should still provide protection
against overflow/underflow. If you want your code to be
maximally portable, don't assume 'int' can store less than
-32767 or greater than 32767.

I agree with Neo that an array of char would be better and
more flexible. But you still need to remember to protect
against overflowing your array.

-Mike
Nov 14 '05 #8
On Mon, 03 Jan 2005 06:36:42 -0500, "beginner10"
<pe************@yahoo.com> wrote:
How can i changhe this code showing how many persons i saved to the file?
And it prints pretty much rubbish. Where is the problem?

#include <stdio.h>
int main()
int main(void)
{
int i;
FILE *data_file;
char list[] = "list.txt";

struct person {
char firstname[20];
char lastname[25];
int phonenumber;
This is a poor choice of data type for phonenumber. See below.

};

struct person person_list[50];
Quick note: Do avoid using "magic constants." Instead, use macros with
meaningful names, e.g.,

#define FNAME_LEN 20
#define LNAME_LEN 25
#define PHONENUM_LEN 7
#define MAX_PERSON_LIST 50

struct person
{
char firstname[FNAME_LEN];
char lastname[LNAME_LEN];
char phonenumber[PHONENUM_LEN]
};

struct person person_list[MAX_PERSON_LIST];

The advantage is the code is easier to read and maintain. What if you
later decided to store the entire 11-digit phone number? All you need
do is edit the PHONENUM_LEN macro definition and recompile, instead of
searching your entire code for occurrences of "7."

for(i=0; i<1; i++) {
This loop will execute only ONCE.

printf("Give your firstname:");
scanf("%s", person_list[i].firstname);
This will break if whitespace is part of the name--scanf stops scanning.

This will break if the user enters more than 19 characters for the
name--scanf will happily allow one to overflow buffers.

Use fgets instead of scanf for more robust data entry.
printf("Give your lastname:");
scanf("%s", person_list[i].lastname);

printf("Give your phone number:");
scanf("%d", &person_list[i].phonenumber);
A telephone number may not necessarily be represented as an integer.
Even if it were, the degree of precision on a given platform may still
make an integer a poor choice for a phone number.

What if the phone number were 9991212? On many platforms, this number
will overflow a signed int.

Result: Potential (probable) rubbish.

Consider using a string instead.
}

if ((data_file = fopen(list, "w")) == NULL) {
printf("Error opening file");
return 0;
} else {

for(i=0; i<=2; i++)
This loop will execute three times, but you still only have ONE
populated person_list[] array index--see the previous for loop.

The remaining 49 person_list[] indices are full of uninitialized,
unpredictable garbage.

Result: Definitely rubbish, as you are now dancing on the head of the UB
daemon. With cleats on.
{
fprintf(data_file, "%s %s %d\n", person_list[i].firstname,
person_list[i].lastname, person_list[i].phonenumber);
}
}
fclose(data_file);
printf("Data saved succesfully!");
return 0;
}


You'll still want some way to determine when to stop adding entries to
your person_list[] array, won't you? You will also want to be able to
read your newly-created data file and display the entries within it.
--
Robert B. Clark (email ROT13'ed)
Visit ClarkWehyr Enterprises On-Line at http://www.3clarks.com/ClarkWehyr/
Nov 14 '05 #9
On Mon, 03 Jan 2005 13:06:26 -0500, in comp.lang.c , Robert B. Clark
<ep****@3pynexf.pbz> wrote:
On Mon, 03 Jan 2005 06:36:42 -0500, "beginner10"
<pe************@yahoo.com> wrote:
int phonenumber;


This is a poor choice of data type for phonenumber. See below.


Depends - many company internal switchboards can handle up to 9999 numbers.
Int works for that.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #10
I'm so out of this! This got 23 errors. Can you help me more?
#define FNAME_LEN 20
#define LNAME_LEN 25
#define PHONENUM_LEN 7
#define MAX_PERSON_LIST 50

struct person
{
char firstname[FNAME_LEN];
char lastname[LNAME_LEN];
char phonenumber[PHONENUM_LEN];
};

struct person person_list[MAX_PERSON_LIST];
for(i=0; i<1; i++) {

printf("Give your firstname:");
scanf("%s", person_list[i].firstname);
printf("Give your lastname:");
scanf("%s", person_list[i].lastname);

printf("Give your phone number:");
scanf("%d", &person_list[i].phonenumber);
}
if ((data_file = fopen(list, "w")) == NULL) {
printf("Error opening file");
return 0;
} else {

for(i=0; i<=2; i++)

{
fprintf(data_file, "%s %s %d\n", person_list[i].firstname,
person_list[i].lastname, person_list[i].phonenumber);
}
}
fclose(data_file);
printf("Data saved succesfully!");
return 0;

Nov 14 '05 #11
I'm so out of this! This got 23 errors. Can you help me more?
#define FNAME_LEN 20
#define LNAME_LEN 25
#define PHONENUM_LEN 7
#define MAX_PERSON_LIST 50

struct person
{
char firstname[FNAME_LEN];
char lastname[LNAME_LEN];
char phonenumber[PHONENUM_LEN];
};

struct person person_list[MAX_PERSON_LIST];
for(i=0; i<1; i++) {

printf("Give your firstname:");
scanf("%s", person_list[i].firstname);
printf("Give your lastname:");
scanf("%s", person_list[i].lastname);

printf("Give your phone number:");
scanf("%d", &person_list[i].phonenumber);
}
if ((data_file = fopen(list, "w")) == NULL) {
printf("Error opening file");
return 0;
} else {

for(i=0; i<=2; i++)

{
fprintf(data_file, "%s %s %d\n", person_list[i].firstname,
person_list[i].lastname, person_list[i].phonenumber);
}
}
fclose(data_file);
printf("Data saved succesfully!");
return 0;

Nov 14 '05 #12
"Mike Wahler" <mk******@mkwahler.net> wrote:
"Neo" <ti***************@yahoo.com> wrote in message

"beginner10" <pe************@yahoo.com> wrote in message
int phonenumber;


better to use char array for phonenumber field too....
lets say user input something like : 9899325025
then it will overflow and store wrong information.
by using char array you have more precise control
over how many digits you want to store in phonenumber
field.


What he means is that you're only guaranteed (by the
language standard) a range of values for type 'int' from
-32767 to 32767 inclusive. Attempts to store a value outside
the range of a signed integer type will produce undefined
behavior.


Moreover, leading zeroes disappear in integers. Since you use
scanf("%d"), an input of 012345 has exactly the same meaning to your
program as 12345. As telephone numbers, however, those mean completely
different things in many places. A telephone number really is not a
number at all; it is a string of symbols, which just happen usually to
be all digits.
If your "telephone number" is an extension number, an int just might be
sufficient; but in that case, this should be clear from the code.

(As an amusing side note, had you used scanf("%i") instead, 012345 would
not have been the same to your program as 12345 - but it would have been
identical to an input of 5349!)

Richard
Nov 14 '05 #13
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/
Nov 14 '05 #14
"beginner10" <pe************@yahoo.com> wrote in message news:<e8******************************@localhost.t alkaboutprogramming.com>...
printf("Give your firstname:");
scanf("%s", person_list[i].firstname);
printf("Give your lastname:");
scanf("%s", person_list[i].lastname);

printf("Give your phone number:");
scanf("%d", &person_list[i].phonenumber);
}
if ((data_file = fopen(list, "w")) == NULL) {
printf("Error opening file");
return 0;
} else {

for(i=0; i<=2; i++)

{
fprintf(data_file, "%s %s %d\n", person_list[i].firstname,
person_list[i].lastname, person_list[i].phonenumber);
}
}
fclose(data_file);
printf("Data saved succesfully!");
return 0;


dear dont give up so soon.............. btw where is ur main() in this whole code...
Nov 14 '05 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Vishnu | last post by:
I have a strange problem on WindowsXP proffessional with IE6 ,when i try to display a tiff file ,it is not showing ,small red x is comming up. I tried by dowloading latest IE from microsoft but...
2
by: c.anandkumar | last post by:
Hi All - I have some problems getting a small piece of javascript working correctly for Firefox. Here is what I am trying to do - 1. I have a form (like a search form) 2. I have many groups...
1
by: Amber | last post by:
The DataGrid allows you to make columns visible or invisible on demand - even edit and other special columns. This article will show you how it is done. Some developers have reported problems...
1
by: bhavik | last post by:
hi I have problem with attachment showing form server side. when our application run on localhost we add any attachment to mail server. if suppose we want to show that attachment we can see...
0
by: ikhan | last post by:
Hello, I am using an activex control on my website. It was running fine with framework 1.1, when I try to run it on framework 2.0 it's not showing up. It's not showing any error message, just a...
10
by: bessington | last post by:
hey all, i'm having a rather bizarre problem.. the image tag i have declared in my xhtml is not showing in safari / konqueror but showing just fine in Firefox, IE, Opera... this is a complete...
3
by: Sandeep Singh Sekhon | last post by:
I am developing an application in ASP.NET 1.1. on one page I allow the user to upload and delete the files to the server. When I delete the file, I physically delete the file from the location....
3
by: Torben Laursen | last post by:
I have a COM shared add-in written in C# that I use in Excel. One of the thinks that the user can do is to open some winforms. The problem that I have is that the first time the user opens a...
5
by: Wayne | last post by:
Several of my Access 2003 databases are exhibiting the same problem under Windows Vista. Charts in forms are not showing any data. Reports are not affected. Charts in reports display as they...
1
by: srinivasarao yarru | last post by:
hi friends, i am getting one problem in my software can you plz try to currect that thing. In my project total 5 tables are there.from table 3 onwards i gave composite primarey key. ...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.