473,811 Members | 1,693 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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_fi le, "%s %s %d\n", person_list[i].firstname,
person_list[i].lastname, person_list[i].phonenumber);
}
}
fclose(data_fil e);
printf("Data saved succesfully!");
return 0;
}
Nov 14 '05 #1
14 1820
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_fi le, "%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_fi le, "%s %s %d\n", person_list[i].firstname,
person_list[i].lastname, person_list[i].phonenumber);
}
}
fclose(data_fil e);
printf("Data saved succesfully!");
return 0;
}

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

"beginner10 " <pe************ @yahoo.com> wrote in message
news:d9******** *************** *******@localho st.talkaboutpro gramming.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_fi le, "%s %s %d\n", person_list[i].firstname,
person_list[i].lastname, person_list[i].phonenumber);
}
}
fclose(data_fil e);
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******** *************** *******@localho st.talkaboutpro gramming.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******** *************** *******@localho st.talkaboutpro gramming.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******** *****@individua l.net...
"beginner10 " <pe************ @yahoo.com> wrote in message

news:d9******** *************** *******@localho st.talkaboutpro gramming.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_fi le, "%s %s %d\n", person_list[i].firstname,
person_list[i].lastname, person_list[i].phonenumber);
}
}
fclose(data_fil e);
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

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

Similar topics

4
7334
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 no use. This is working fine on win2k IE6 Here is the html file I am using to display the tif file <html> <head>
2
2227
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 of searchable fields in the fields 3. Each group can be expanded/collapsed by clicking on a link "(Fewer|More) Options" which sits right next to the group title.
1
840
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 controlling the visibility of columns in the DataGrid control. The problem usually comes down to one fact. The DataGrid has a property called AutoGenerateColumns. The default value is "True". This means that when AutoGenerateColumns is set to True,...
1
1350
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 that attachment with View button. so in view button I me giving path of local machine and attachment will be showing. but..... when I upload that application on server machine and when I click
0
1245
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 "image not found icon" in webpage's body and "DONE" on IE's status bar. When switch it to framwork 1.1 it runs fine. What I think for the activeX not showing issue is that this might be some security issue because I had the same problem earlier...
10
2165
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 mystery and I have been scouring every book / resource I can find but haven't come up with an answer. any one have any ideas? all other images in site showing fine - but they are declared as background images in the css. the site is:...
3
1559
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. Then I again prompt the user to load a new file but I save the file with the same name the earlier image file had been saved. The problem is that when I again upload the page through Response.Redirect after uploading, it is showing the same image it...
3
3366
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 winform it is slow around 7 seconds and after that it takes no time. Is there a way to speed up the process to show the winform the first time? Thanks Torben
5
5206
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 should. The chart object in forms appears but contains no data. It appears to be a screen painting problem because if I open a report or another form on top of the form that is not showing the chart, when the second report or form is closed, the...
1
1443
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. table3's corresponding form is Form3 in this form first i entered 1st record and then click add record button then i am getting new form but previous entered record fields disablity also it is showing in the new form.but entry time there is no...
0
9728
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10389
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10402
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7670
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6890
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5554
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5692
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3867
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.