-

Jump to content



Photo
- - - - -

Help with C Programming Assignment


This topic has been archived. This means that you cannot reply to this topic.
28 replies to this topic

#1 of 29 Andrew S

Andrew S

    Stunt Coordinator

  • 215 posts
  • Join Date: Sep 30 2001

Posted November 30 2004 - 10:10 AM

If this is in the wrong forum I apologize, but I've seen other homework-related threads in here.

My program has to do with sports stats. The user will enter a game's results in the format:
team1,team2,score1,score2,
E.g.
blue,red,11,16,

I need to write a function that reads this input and returns the values for team1, team2, score1, score2 as four strings.

I know how to separate each part of the string, I just can't for the life of me figure out how to send and modify/return strings within a function. I could do it outside the function, but this will be repeated for 28 games and the use of a function is part of the assignment.

If anyone can point me towards an example on the internet or could help me out here, it would be greatly appreciated.

Thanks,
Andrew
-
Wish I had more money

#2 of 29 Jeff Cooper

Jeff Cooper

    Screenwriter

  • 1,247 posts
  • Join Date: Mar 06 2000

Posted November 30 2004 - 10:24 AM

If i'm understanding you correctly, then you could pass in the four strings by reference into the function, and assgin to each string within the function. You wouldn't use the functions return value, or you could use the return value as a boolean telling you whether the function succeeded or not.
-Jeff Cooper

"Curse you inspector Dim! You are too clever for us naughty people."

#3 of 29 Sami Kallio

Sami Kallio

    Screenwriter

  • 1,035 posts
  • Join Date: Jan 06 2004

Posted November 30 2004 - 10:41 AM

void foo (char* p_strTeam1, char* p_strTeam2, char* p_strScore1, char* p_strScore2)
{
strcpy(p_strTeam1, "Minnesota");
strcpy(p_strTeam2, "Dallas");
strcpy(p_strScore1, "101");
strcpy(p_strScore2, "0");
}

Remember to allocate memory to the strings before passing them to the function.

#4 of 29 Andrew S

Andrew S

    Stunt Coordinator

  • 215 posts
  • Join Date: Sep 30 2001

Posted November 30 2004 - 10:51 AM

I'm really new to all this programming stuff, and I'm not understanding some of the terminology. What I want to do is similar to this example my teacher gave us that involving an array.

#include
#include
#define SIZE 10
void fillArray(int a[]);
int main()
{
int x, array[SIZE];

for (x=0; x array[x]=0;
fillArray(array);

for (x=0; x printf("%dn", array[x]);

system("PAUSE");
return 0;
}

/***************function***************/

//void fillArray(int a[])
void fillArray(int *a)
{
int i;

for(i=0; i a[i]=i;
}

In my case, I want to manipulate the strings team1, team2, score1, and score2 instead of the array "array" in the example above.

I want send my function the entire string entered by the user, "blue,red,12,11" for example, which will then separate each significant piece and return say, "blue" as the string team1, "red" as team2, "11" as score1, and "12" as the score2, which I can then repeat for 28 games and use to update a table of statistics.

I'm just not sure how to manipulate my four strings within the function, or even how to send them to the function.

I'm sorry for the long read, but I'm really new to this.
Thanks,
Andrew
-
Wish I had more money

#5 of 29 Sami Kallio

Sami Kallio

    Screenwriter

  • 1,035 posts
  • Join Date: Jan 06 2004

Posted November 30 2004 - 11:10 AM

You can pass the strings as pointers like in the example I gave you. You define it first:

char strTeam[MAX_LENGTH_OF_TEAM_NAME];

Then you pass the first character to the function:

GetTeamName (strTeam); // strTeam points to strTeam[0]

void GetTeamName (char* p_strTeamName)
{
...
}

As for manipulating strings, look up functions 'strcspn' and strcpy. Get started with these and let us know what you have came up with. We'll help you from there. I don't really want to give out the answer without you trying to work it out first, that way you will learn more than just copying.

#6 of 29 Andrew S

Andrew S

    Stunt Coordinator

  • 215 posts
  • Join Date: Sep 30 2001

Posted November 30 2004 - 11:21 AM

Much appreciated Sam and Jeff, I'll play around with that.
Thanks again,
Andrew
-
Wish I had more money

#7 of 29 BrianW

BrianW

    Screenwriter

  • 2,552 posts
  • Join Date: Jan 30 1999

Posted November 30 2004 - 03:28 PM

Whatever you do, remember that local variables go away after the function is done.

For instance:

char * ParseString(char *stringToParse)
{
....char tempStringBuffer[MAX_STRING_LENGTH];

//Set tempStringBuffer to some string value...

....return tempStringBuffer;
}

(Note that I used periods to facilitate indentation.) Returning the pointer to the local variable tempStringBuffer may actually work some (or even most or all) of the time, but the memory occupied by the local variable in any function is returned to the stack for other functions to use. Therefore, the local variable (a variable declared inside a function) itself is undefined by the time the calling function gets a pointer to it.

You'll need to pass pointers to the strings you want to fill in, as described above.

If your instructor wants you to demonstrate function re-use, then may I suggest the following:


char inputString[] = "blue,red,11,14";
int returnCode;

int ParseString(char *stringToParse, char *stringToFill, int index)
{
....int errorCode = 0;

//Index is 1 to 4 (or 0 to 3) and specifies which segment of the stringToParse is copied to the stringToFill.

....return errorCode;
}

returnCode = ParseString(inputString,team1,1);

returnCode = ParseString(inputString,team2,2);

returnCode = ParseString(inputString,score1,3);

returnCode = ParseString(inputString,score2,4);


Use less- (or more-) pedantic names in the style of your (or your instructor's) choice, or course.

Be sure to check for proper values of index in the parsing function and return an error code for each thing that can go wrong. This kind of re-use and error checking/reporting usually impresses programming instructors.

Good luck.
-Brian
Come, Rubidia. Let's blow this epoch.

#8 of 29 Sami Kallio

Sami Kallio

    Screenwriter

  • 1,035 posts
  • Join Date: Jan 06 2004

Posted December 01 2004 - 12:50 AM

Andrew, are you working with C or C++? If you're using C++ then you might want to impress your professor with function overloading. I really don't want to take you away from the main problem but you could implement three interfaces and measure the time it takes each three to execute.

Once you have solved this one way, I will tell another interface solution to go with Brian's suggestion.

Have you made any progress yet? Just let us know if you need help.

#9 of 29 Andrew S

Andrew S

    Stunt Coordinator

  • 215 posts
  • Join Date: Sep 30 2001

Posted December 01 2004 - 04:43 AM

I'm working with C. It's just a general first year course for engineers. I've made progress and generally know what I'm doing now. I think I'll get the rest of it working, I don't know if it'll be as efficient as it could be, but we don't get marked for efficiency, so it all works out.

Really do appreciate all the help and suggestions.
Thanks again,
Andrew
-
Wish I had more money

#10 of 29 Jeff Gatie

Jeff Gatie

    Lead Actor

  • 6,529 posts
  • Join Date: Aug 19 2002

Posted December 01 2004 - 05:34 AM

Paul's scanf routine will work.

I'd substitute

char param1[20];

(param2, param3, etc) for the malloc's because you probably have not covered dynamic memory allocation yet or skip the 'param' strings altogether and do it like this

scanf("%s,%s,%s,%s", team1, team2, score1, score2);

it is essentially the same thing assuming the user input does not go crazy and overflow the array. Which leads me to this caution - in 15 years of writing in 'C', I have never used a scanf to do user input. I have found they are notorious for blowing up when the user does not follow directions (i.e lousy error handling) and they are never that portable from system to system. I stick with the string and char input functions from stdio.h, which make it easier to limit input by overzealous users. Better yet, make up your own APL of input functions that check for and report errors.

That caution aside, this assignment is tailor made for a scanf, so I would not hesitate to use it because that's probably what the prof. wants.

#11 of 29 Jeff Gatie

Jeff Gatie

    Lead Actor

  • 6,529 posts
  • Join Date: Aug 19 2002

Posted December 01 2004 - 05:48 AM

Paul, you are correct, but my example assumed what you wrote in your expanded code. Of course if the char * are not allocated by definition before the call to the function, they are going to go out of scope. Being this is a first year course, I assumed they were not using malloc yet and wrote my example to account for that. My first example (the 'char param1[20]' stuff) I should have included a memcpy or strncpy for each param to team, score etc., you are correct about the scope on that one (but hey, we can't give him all the answers).

#12 of 29 Andrew W

Andrew W

    Supporting Actor

  • 532 posts
  • Join Date: Jun 19 2001

Posted December 01 2004 - 06:56 AM

It would be much cleaner overall to use strtok() defining the comma as the delimiter.

Also, you can return a pointer to a static array or to malloc()ed memory

char* fn()
{
static char buff[] = "string";
return buff;
}
Andrew in Austin

#13 of 29 Jeff Gatie

Jeff Gatie

    Lead Actor

  • 6,529 posts
  • Join Date: Aug 19 2002

Posted December 01 2004 - 07:02 AM

Quote:
It would be much cleaner overall to use strtok() defining the comma as the delimiter.


I agree, use gets to input the string and then strtok to parse it. That's the way I would do it, but being a beginner's course, I just think the prof. is screaming for scanf here. There's more than one way to skin a cat and sometimes something worth doing is not worth doing pretty (or well, depending on the deadline). Posted Image

#14 of 29 Jeff Gatie

Jeff Gatie

    Lead Actor

  • 6,529 posts
  • Join Date: Aug 19 2002

Posted December 01 2004 - 07:10 AM

Yep, always use a tmp pointer when using strtok, unless you want your original string to go off to oblivion (actually, I think it just null terminates it on most systems).

Note - you have to physically copy into the tmp string, not just assign it, to save the original.

Edit - Andrew, let me take this time to advise you to get the only 'C' programming book you will ever need - "The C Programming Language" by Kernighan and Ritchie, affectionately known as "K&R". I have mine from 1988 and still use it 2-3 times a week. Any other book I've bought has long since been shelved.

#15 of 29 Andrew S

Andrew S

    Stunt Coordinator

  • 215 posts
  • Join Date: Sep 30 2001

Posted December 01 2004 - 07:35 AM

Yeah, the programming book recommended by the prof has ben absolutely useless. Hardly any examples at all, just a lot of reading, which is what you don't need when you're looking for the format of things. I looked at it once and threw it to the corner of my room. Just another lesson learned - do not buy all of your books right away!!!

And on a sidenote, I have the main part of the program working right now. Like I said, don't know if it works efficiently, but it works, which is more than I thought it would at this point. Thanks again.

Andrew
-
Wish I had more money

#16 of 29 D. Scott MacDonald

D. Scott MacDonald

    Supporting Actor

  • 545 posts
  • Join Date: Oct 10 1999

Posted December 01 2004 - 07:36 AM

The other issue with using the local variables is that it opens a wide hole for buffers overruns and security issues. I realize that this is not an issue for this assignment, but since we're all showing off our geekiness...
Scott

#17 of 29 Jeff Gatie

Jeff Gatie

    Lead Actor

  • 6,529 posts
  • Join Date: Aug 19 2002

Posted December 01 2004 - 08:06 AM

Yeah, K&R is not heavy on examples, but it is the reference for syntax, formatting, function definitions, etc. It is definitely not a 'concept' examples type book, but then 'C' is not a very concept based language at it's core, it really is very simple. Because it is so simple and sparse, it very is flexible; but it also does not do a lot of handholding. That is up to the programmer. The examples that are in K&R give the beginnings of programming concepts, but you have to build on them on your own. But that is the beauty of computer science, if you had to have everything written down for you, you'd have become an accountant.Posted Image

#18 of 29 Greg_R

Greg_R

    Screenwriter

  • 1,998 posts
  • Join Date: Apr 09 2000
  • Real Name:Greg
  • LocationPortland, OR

Posted December 01 2004 - 11:37 AM

Yes, get the K&R book. However, I would also strongly recommend this book for Unix C programming. It has tons of examples and I find myself using it more than the K&R book. My job is more engineering (not programming) so I find the examples helpful when I have to write a C program (95% of my coding is done in Perl).

#19 of 29 LDfan

LDfan

    Supporting Actor

  • 724 posts
  • Join Date: Nov 30 1998

Posted December 01 2004 - 12:01 PM

I've always wanted to learn C programming but even the local community college has switched all its computer science courses to Java. Guess I might have to teach myself instead.


Jeff

#20 of 29 BrianW

BrianW

    Screenwriter

  • 2,552 posts
  • Join Date: Jan 30 1999

Posted December 01 2004 - 12:20 PM

What Jeff said. Learning syntax is not the same as learning how to program. I knew a programmer (he made a living at this!!!) who just couldn't get it in his head that declaring a character pointer did NOT allocate space for a string. After six months of copying strings to uninitialized pointers, our company finally had to let him go. Strictly speaking, his syntax was completely correct, and the compiler (which wasn't too clever - this was years ago, mind you, when compilers checked nothing but syntax) didn't complain.

Also, not that it would be of interest to a first-year programming student, but some (though not all) implementations of strtok() should be avoided in a multi-threaded environment because they use unsecured global resources. This function, along with a handful of others, did not lend itself to being redesigned for use in multi-threaded fashion, so many old timers like me just learned to do without in the brave new world.

Keep us posted on your progress.
-Brian
Come, Rubidia. Let's blow this epoch.