What's new

Help with C Programming Assignment (1 Viewer)

Andrew S

Stunt Coordinator
Joined
Sep 30, 2001
Messages
214
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
 

Jeff Cooper

Senior HTF Member
Joined
Mar 6, 2000
Messages
3,016
Location
Little Elm, TX
Real Name
Jeff Cooper
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.
 

Sami Kallio

Screenwriter
Joined
Jan 6, 2004
Messages
1,035
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.
 

Andrew S

Stunt Coordinator
Joined
Sep 30, 2001
Messages
214
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
 

Sami Kallio

Screenwriter
Joined
Jan 6, 2004
Messages
1,035
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.
 

BrianW

Senior HTF Member
Joined
Jan 30, 1999
Messages
2,563
Real Name
Brian
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.
 

Sami Kallio

Screenwriter
Joined
Jan 6, 2004
Messages
1,035
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.
 

Andrew S

Stunt Coordinator
Joined
Sep 30, 2001
Messages
214
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
 

Jeff Gatie

Senior HTF Member
Joined
Aug 19, 2002
Messages
6,531
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.
 

Jeff Gatie

Senior HTF Member
Joined
Aug 19, 2002
Messages
6,531
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).
 

Andrew W

Supporting Actor
Joined
Jun 19, 2001
Messages
531
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;
}
 

Jeff Gatie

Senior HTF Member
Joined
Aug 19, 2002
Messages
6,531


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). :D
 

Jeff Gatie

Senior HTF Member
Joined
Aug 19, 2002
Messages
6,531
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.
 

Andrew S

Stunt Coordinator
Joined
Sep 30, 2001
Messages
214
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
 

D. Scott MacDonald

Supporting Actor
Joined
Oct 10, 1999
Messages
545
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...
 

Jeff Gatie

Senior HTF Member
Joined
Aug 19, 2002
Messages
6,531
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.:D
 

Greg_R

Screenwriter
Joined
Apr 9, 2000
Messages
1,996
Location
Portland, OR
Real Name
Greg
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).
 

LDfan

Supporting Actor
Joined
Nov 30, 1998
Messages
724
Real Name
Jeffrey
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
 

BrianW

Senior HTF Member
Joined
Jan 30, 1999
Messages
2,563
Real Name
Brian
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.
 

Users who are viewing this thread

Sign up for our newsletter

and receive essential news, curated deals, and much more







You will only receive emails from us. We will never sell or distribute your email address to third party companies at any time.

Forum statistics

Threads
357,057
Messages
5,129,739
Members
144,280
Latest member
blitz
Recent bookmarks
0
Top