I will have a exam on the oncoming friday, my professor told us that it
will base upon this program. i am having troubles understanding this
program, for example what if i want to add all the total calories that
the user input together. determine which food has the largest calories.
how do i start to modifiy the program inorder to do the things i listed
above. thanks
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int calories;
int group;
} FOOD;
void getFood(FOOD foods[ ], int i ) {
FOOD newFood;
void *characters = malloc(81*sizeof(char));
printf("\nPlease enter the requested information:\n");
printf(" for food item %d, what is\n", i+1);
printf(" the name? ");
gets( characters); // NOTE fgets IS BETTER!
newFood.name = characters;
printf(" calories/serving? ");
scanf("%d", &(newFood.calories));
printf(" food group? ");
scanf("%d", &(newFood.group));
printf("\n");
foods[i] = newFood;
} // end getFood // note:a struct is and lvalue !!
void dump( FOOD foods[ ] , int n ) {
int i;
for(i=0; i<n; i++ ) {
printf("Food %d is: \n", i+1);
printf(" name : %s\n", foods[i].name);
printf(" calories: %d\n", foods[i].calories);
printf(" group # : %d\n", foods[i].group);
printf("\n");
} // end for
} // end dump
int main( ) {
int num; // number of foods entered
int i;
char dum[81];
printf("\nHow many foods will you enter? ");
scanf("%d", &num);
FOOD foods[num];
for( i=0; i<num; i++ ) {
gets(dum); //NOTE: THIS IS HERE BECAUSE OF SCANF
getFood( foods, i );
} // end for
dump( foods, num);
return 0;
} // end main 26 2070
like this:
//......
int total_calories;
int maxcalories;
char maxcaloriesname[81]
//......
total_calories=0;
maxcalories=0;
strcpy(maxcaloriesname,"no");
//......
FOOD foods[num];
for( i=0; i<num; i++ ) {
getFood( foods, i );
// .......
total_calories+=foods[i].calories;
if(foods[i].calories>maxcalories)
{
maxcalories=foods[i].calories;
strcpy(maxcaloriesname,foods[i].name);
}
} // end for
//.....
Bail wrote: I will have a exam on the oncoming friday, my professor told us that it will base upon this program.
I had whipped up some code, which works, and pasted it only to
discover, its
thursday!
i am having troubles understanding this program, for example what if i want to add all the total calories that the user input together. determine which food has the largest calories. how do i start to modifiy the program inorder to do the things i listed above. thanks
[just too many things I felt i had to comment on so ... ]
1. Don't use gets. Its dangerous. GIYF.
2. Interactive input with scanf is tricky stuff. Search the archive,
with something
like "scanf + string + input + pete ". (pete happens to post some
code I really like)
3. Learn about qsort(). Here's some hint: you will need something like
....
int calcmp( const void *l, const void *r )
{
const FOOD *left = l;
const FOOD *right = r;
if ( left->calories > right->calories )
return 1;
/* fill in the blanks ... */
}
4. You said you're having trouble. Presumably, not with the code you
pasted.
If you understand the code you pasted, the homework should be easy
:)
See ya' on friday.
Suman wrote: 2. Interactive input with scanf is tricky stuff. Search the archive, with something like "scanf + string + input + pete ". (pete happens to post some code I really like)
That way of using scanf, was primarily promoted by Dan Pop.
Dan Pop tended to be very accuarate, but was ...
If I were to say that he had an abrasive personality,
it would not surprise me in the least,
if he were to reply with a logical rebuttal
of how his personality was not abrasive
and how I must be mentally deficient
for even thinking something like that.
--
pete
pete wrote:
[...my ignorance snipped] That way of using scanf, was primarily promoted by Dan Pop. Dan Pop tended to be very accuarate, but was ...
Hmm. Appears that I just found much the same. But of course,
post-posting.
If I were to say that he had an abrasive personality, it would not surprise me in the least, if he were to reply with a logical rebuttal of how his personality was not abrasive and how I must be mentally deficient for even thinking something like that.
And I thought I'm the only Ogden Nash fan 'round here.
huh? i dont get where to put this code into my program to make it work?
pete wrote: Suman wrote:
2. Interactive input with scanf is tricky stuff. Search the archive, with something like "scanf + string + input + pete ". (pete happens to post some code I really like)
That way of using scanf, was primarily promoted by Dan Pop. Dan Pop tended to be very accuarate, but was ...
<snip very accurate description> :-)
Indeed...What ever happened to Dan?
Come on some one help me out here.... dont get this stuffs.
thanks for the info. is there any more ??? help a poor student here
Bail wrote: thanks for the info. is there any more ??? help a poor student here
What info?
Brian
--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
will someone take the time to explain to me how does the program i
posted above work? and how do i start modifiy the program inorder to
calculate the total calories, max calories. ???
In article <11**********************@o13g2000cwo.googlegroups .com>,
Bail <Ba********@gmail.com> wrote:
:huh? i dont get where to put this code into my program to make it work?
You would put it in at the point that you wanted to,
"add all the total calories that
the user input together. determine which food has the largest calories."
--
Okay, buzzwords only. Two syllables, tops. -- Laurie Anderson
In article <11*********************@g47g2000cwa.googlegroups. com>,
Bail <Ba********@gmail.com> wrote: will someone take the time to explain to me how does the program i posted above work? and how do i start modifiy the program inorder to calculate the total calories, max calories. ???
What part of it don't you understand? Do you understand basic
operations with structures? Do you understand the following? If not,
what *specific* lines do you not understand, and what is your best
guess about what those lines are supposed to do?
#include <stdio.h>
typedef struct { int foodno; float foodcalories } FOOD;
void describefood( FOOD thefood ) {
printf( "Food #%d has %f Calories\n", thefood.foodno, thefood.foodcalories );
}
void describefoodptr( FOOD *thefoodptr ) {
printf( "Food #%d has %f Calories\n", thefoodptr->foodno,
thefoodptr->foodcalories );
}
int main(void) {
FOOD firstfood, secondfood;
firstfood.foodno = 1;
firstfood.foodcalories = 1187.3;
secondfood.foodno = 2;
secondfood.foodcalories = 831.88;
describefood( firstfood );
describefoodptr( &secondfood );
}
--
Okay, buzzwords only. Two syllables, tops. -- Laurie Anderson
void describefoodptr( FOOD *thefoodptr ) {
printf( "Food #%d has %f Calories\n", thefoodptr->foodno,
thefoodptr->foodcalories );
}
thefoodptr->foodno???
Suman wrote: pete wrote: If I were to say that he had an abrasive personality, it would not surprise me in the least, if he were to reply with a logical rebuttal of how his personality was not abrasive and how I must be mentally deficient for even thinking something like that.
And I thought I'm the only Ogden Nash fan 'round here.
Most of my English text is in free verse,
and all of my C code is.
--
pete
Bail wrote:
You cut out typedef struct { int foodno; float foodcalories } FOOD;
and other relevant stuff. From a common sig around comp.lang.c atm:
`Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.'
It's clearer to others what you mean when you quote the bits you're
talking about. Anyway...
void describefoodptr( FOOD *thefoodptr ) { printf( "Food #%d has %f Calories\n", thefoodptr->foodno, thefoodptr->foodcalories );
}
thefoodptr->foodno???
FOOD is a typedef for the struct:
typedef struct { int foodno; float foodcalories } FOOD;
An instance of FOOD has members foodno (an integer) and
foodcalories (a float).
If you declared an instance like
FOOD myfood;
You would access those members with:
myfood.foodno
and
myfood.foodcalories
The function you are talking about takes a parameter
(FOOD *thefoodptr)
So thefoodptr is a pointer to an instance of FOOD.
You dereference it to get an instance of food like this:
*thefoodptr /* now an instance of FOOD */
And would get at the members like this:
(*thefoodptr).foodno
and
(*thefoodptr).foodcalories
Except this is an awful syntax, so there is a shorthand
thefoodptr->foodno
The -> means dereference the object to the left (to hopefully
get an instance of a struct) then access the member with the
name on the right.
--
imalone
Bail wrote: will someone take the time to explain to me how does the program i posted above work?
There is no program above. Please read one of the over 1000 messages on
this group telling you how to provide context using Google. A search for
the terms "Google context" will find them.
You cannot assume that people have seen previous messages, because they
may not have, nor that they will remember them if they have seen them.
and how do i start modifiy the program inorder to calculate the total calories, max calories. ???
Load it in to an editor is all I can suggest since I don't have the code
you want to modify.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Bail <Ba********@gmail.com> wrote: void describefoodptr( FOOD *thefoodptr ) { printf( "Food #%d has %f Calories\n", thefoodptr->foodno, thefoodptr->foodcalories );
}
thefoodptr->foodno???
If you need to learn C you should simply go and do it. You cannot learn
from a newsgroup if you don't get the basics at all.
You'ld better look into your C book (if you don't have one, don't bother
to write the exame at all). If you have certain questions about the
-> operator for example somebody in this ng will surely answer it.
Though you should note, that most are not willing to do your homework.
--
Z (zo**********@web.de)
"LISP is worth learning for the profound enlightenment experience
you will have when you finally get it; that experience will make you
a better programmer for the rest of your days." -- Eric S. Raymond
Bail wrote: will someone take the time to explain to me how does the program i posted above work? and how do i start modifiy the program inorder to calculate the total calories, max calories. ???
Not until you learn to post correctly. SEE BELOW.
Brian
--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
pete said: Suman wrote: And I thought I'm the only Ogden Nash fan 'round here.
Most of my English text is in free verse, and all of my C code is.
Code is never free;
Constrained by mathematics,
Like a flower's leaves.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999 http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Richard Heathfield <in*****@invalid.invalid> writes: pete said: Suman wrote: And I thought I'm the only Ogden Nash fan 'round here.
Most of my English text is in free verse, and all of my C code is.
Code is never free; Constrained by mathematics, Like a flower's leaves.
*applause*
--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Richard Heathfield wrote: pete said:
Suman wrote:
And I thought I'm the only Ogden Nash fan 'round here.
Most of my English text is in free verse, and all of my C code is.
Code is never free; Constrained by mathematics, Like a flower's leaves.
union possible { short prose; short code; }
peculiar, definitely; long shot, granted;
long objections (double take) {
static short idioms,
readability = 0, nothing;
interpunction: peculiar; if (nothing) {} else
but: while (peculiar.prose = definitely.code) continue;
}
signed Skarmander;
Skarmander wrote: Richard Heathfield wrote: pete said:
Suman wrote:
And I thought I'm the only Ogden Nash fan 'round here.
Most of my English text is in free verse, and all of my C code is.
Code is never free; Constrained by mathematics, Like a flower's leaves.
Petals!
Nobody cares about calyxes!!!
--
pete
which C book you suggest i buy?
Bail said: which C book you suggest i buy?
One of these three:
The C Programming Language, 2nd Ed. Kernighan & Ritchie. Prentice Hall,
1988. ISBN 0-13-110362-8 (paperback), or 0-13-110370-9 (hardback).
C Programming: A Modern Approach, K.N.King, W.W.Norton & Company, 1996.
ISBN 0-393-96945-2
C: How to Program, 2nd Ed. Deitel, H.M. & Deitel, P.J. Prentice Hall, 1994.
ISBN: 0-13-226119-7
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999 http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Groovy hepcat Bail was jivin' on 16 Nov 2005 21:02:54 -0800 in
comp.lang.c.
Help on understanding Structs's a cool scene! Dig it! I will have a exam on the oncoming friday, my professor told us that it
I realise I'm too late with this followup, but just in case you're
still wondering about it...
will base upon this program. i am having troubles understanding this
Well, what don't you understand? It's pretty straight forward,
notwithstanding the numerous inadequecies, which I have outlined. Do I
understand correctly that your professor supplied this code? If so, YE
GADS! What's he a professor of, needlepoint?
program, for example what if i want to add all the total calories that the user input together. determine which food has the largest calories. how do i start to modifiy the program inorder to do the things i listed above. thanks
#include <stdio.h> #include <stdlib.h>
typedef struct { char *name; int calories; int group; } FOOD;
void getFood(FOOD foods[ ], int i ) { FOOD newFood; void *characters = malloc(81*sizeof(char));
sizeof(char) is 1.
You *must* check the return value of malloc() for a null pointer
(indicating an error). malloc() can fail, y'know; and when it does,
you must not try to dereference the pointer.
Why is characters a pointer to void? If you want to store characters
in the memory it points at, then wouldn't a pointer to char be better?
printf("\nPlease enter the requested information:\n"); printf(" for food item %d, what is\n", i+1); printf(" the name? ");
This prompt may not be displayed straight away. Use fflush() to
flush stdout to better the chances of seeing the prompt.
fflush(stdout);
gets( characters); // NOTE fgets IS BETTER!
Never use gets(). Just never use gets(). As you (or, presumably your
professor) say in the comment, fgets() is better. Why, then, didn't
you (or he) use fgets()? gets() is a disaster waiting to happen. Never
use it. Use fgets() instead. Never use gets(). Read the FAQ for more
on this; and never use gets(). Just to reiterate: never use gets().
By the way, don't use C++ style comments here. There are (at least)
two good reasons for this. First, many people here still use pre-C99
compilers, which don't support C++ style comments. And second, lines
have a way of wrapping around here. When that happens it makes
cutting, pasting and compiling dificult. Original C comments (/*...*/)
are well behaved when they wrap around. C++ comments are not.
newFood.name = characters;
printf(" calories/serving? ");
This prompt may not be displayed straight away. Use fflush() to
flush stdout to better the chances of seeing the prompt.
fflush(stdout);
scanf("%d", &(newFood.calories));
printf(" food group? ");
This prompt may not be displayed straight away. Use fflush() to
flush stdout to better the chances of seeing the prompt.
fflush(stdout);
scanf("%d", &(newFood.group)); printf("\n"); foods[i] = newFood;
You're not going to return some status value to indicate
success/failure conditions?
} // end getFood // note:a struct is and lvalue !!
What's the point of this useless comment? Comments should make code
clearer, easier to read. They should not just clutter the code with
useless garbage.
void dump( FOOD foods[ ] , int n ) { int i; for(i=0; i<n; i++ ) { printf("Food %d is: \n", i+1); printf(" name : %s\n", foods[i].name); printf(" calories: %d\n", foods[i].calories); printf(" group # : %d\n", foods[i].group); printf("\n"); } // end for } // end dump
More useless comments!
int main( ) { int num; // number of foods entered
And another one!
int i; char dum[81];
printf("\nHow many foods will you enter? ");
This prompt may not be displayed straight away. Use fflush() to
flush stdout to better the chances of seeing the prompt.
fflush(stdout);
scanf("%d", &num);
FOOD foods[num];
Won't work in pre-C99 implementations, where an array's bounds must
be declared by a constant. Instead, you should use malloc() (and do
remember to check the return value).
for( i=0; i<num; i++ ) { gets(dum); //NOTE: THIS IS HERE BECAUSE OF SCANF
Huh? What do you (or your prof) mean? You mean scanf() is leaving a
newline (or other garbage) in the stream to be picked up by the next
input function? Well, then, what does that say about the way you are
using scanf()? What does it say about the whole input strategy? Not
very good, is it? Consult the FAQ on this.
Oh, and by the way, did I mention that you should never use gets()?
Well, you should never use gets().
getFood( foods, i ); } // end for
dump( foods, num);
What about relinquishing the memory allocated in getFood()? Very
poor form, leaving this undone!
return 0;
Poor (inconsistent) indentation! This sort of thing can make code
harder to read.
} // end main
If your professor wrote this code, I'd seriously think about
changing schools. It's horrendous! I'd expect a rank beginner to write
code like that, not a professor (unless he were a professor of
something totally unrelated to programming).
But the logic is pretty simple. Here is a basic breakdown of it.
1) First it asks the user to enter the number of foods he/she wishes
to enter, then reads in that number.
2) Next it creates an array of structures used to hold the food data.
3) Then it goes into a loop that calls a function that
a) asks the user the name of the food and reads in the name, having
first allocated memory in which to store it,
b) asks the user for the number of calories and reads in the
number,
c) asks the user for the food group (a number) and reads in the
number, and
d) stores this information in an element of the array.
4) Lastly it calls a function that displays the information stored in
the array.
--
Dig the even newer still, yet more improved, sig! http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"? This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: cpptutor2000 |
last post by:
I am using an STL list to store data packets in a network simulator.
The data packets are really C structs, which have other C structs
inside them....
|
by: SteveM |
last post by:
This is probably an easy answer but since I am fairly new to C++ for
some reason I can't see it :-( Any help would be appreciated
:-)
I have a...
|
by: Johnny |
last post by:
I need to determine whether a text box contains a value that does not convert
to a decimal. If the value does not convert to a decimal, I want to...
|
by: gtippery |
last post by:
Newbie-ish questions - I've been away from C for a _long_ time.
It seems to me that there ought to be easier (or at least shorter) ways
to do...
|
by: Angel |
last post by:
I'm using several C functions (in a dll) that receive a struct as parameter.
Since I'm doing it in C#, I assume I need to recreate the struct in C#...
|
by: Brian |
last post by:
I am very new to C# programming and have run into a problem.
I apologize for the repost of this article. For some reason, my news
reader...
|
by: ^MisterJingo^ |
last post by:
I'm new to C# (literally 2 days) and need a bit of help understanding
an error.
struct Blah
{
int x;
int y;
public int X
{
|
by: arcticool |
last post by:
I had an interview today and I got destroyed :(
The question was why have a stack and a heap?
I could answer all the practical stuff like value...
|
by: engggirl3000 |
last post by:
I was told to write a function that will read data, in a user defined text file, into a vector of structs. I am not sure where to start with this. ...
|
by: tammygombez |
last post by:
Hey fellow JavaFX developers,
I'm currently working on a project that involves using a ComboBox in JavaFX, and I've run into a bit of an issue....
|
by: tammygombez |
last post by:
Hey everyone!
I've been researching gaming laptops lately, and I must say, they can get pretty expensive. However, I've come across some great...
|
by: better678 |
last post by:
Question:
Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct?
Answer:
Java is an object-oriented...
|
by: teenabhardwaj |
last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
|
by: Kemmylinns12 |
last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
|
by: CD Tom |
last post by:
This happens in runtime 2013 and 2016. When a report is run and then closed a toolbar shows up and the only way to get it to go away is to right...
|
by: Naresh1 |
last post by:
What is WebLogic Admin Training?
WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
|
by: Matthew3360 |
last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
|
by: AndyPSV |
last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
| |