Programming Help

byu

Master
Joined
Dec 18, 2008
Messages
2,021
Location
California
WCA ID
2009YUBR01
YouTube
Visit Channel
I need some help, this is example 2.1 on the ProCo 2008. I've gotten pretty far in about 5 minutes, but I'm having trouble with this one function I'm writing, and I need some help.


LANGUAGE: C
GOAL: I'm writing a function that takes in a character string and if the following two pieces of criteria are met:

1) the word is three letters
2) the second letter is A

then it returns 1. Otherwise, it returns 0. Here is what I have:

Code:
int determine(char word[10]) {
	int fits = 1;
	if (word[3] == '\0')
		fits = 0;
	else if (word[1] != 'A')
		fits = 0;
	return fits;
}

But for some reason, it always returns 0, no matter what, even when I write a word like CAR (not that the character strings will be all capital letters).

Help is appreciated, thanks.
 
Code:
	if (word[3] == '\0')
		fits = 0;
Isn't that backwards? Change "==" to "!=".

Or use strlen(word) == 3. If the string was "\0A\0\0", testing just the 4th character fails (ok, that can't happen in this problem, but I think strlen is clearer).

It's usually a good idea to show full code, including how you're calling the function. Sometimes the problem isn't where you expect it to be.

Edit: Here's how I'd write it:
Code:
#include <string.h>

int ok(const char *word) {
        return strlen(word) == 3 && word[1] == 'A';
}
 
Last edited:
Code:
	if (word[3] == '\0')
		fits = 0;
Isn't that backwards? Change "==" to "!=".

Or use strlen(word) == 3. If the string was "\0A\0\0", testing just the 4th character fails (ok, that can't happen in this problem, but I think strlen is clearer).

It's usually a good idea to show full code, including how you're calling the function. Sometimes the problem isn't where you expect it to be.

Edit: Here's how I'd write it:
Code:
#include <string.h>

int ok(const char *word) {
        return strlen(word) == 3 && word[1] == 'A';
}

I will also note that as a general rule, string handling functions in C should only access characters of a string after all other characters preceding it have been verified to be something other than the null character. For example, if the literal string "A" were passed to the function, accessing word[3] in the function could theoretically (although not very likely) result in a memory exception, causing the program to crash. Johannes's code used the strlen function as a convenient way of ensuring word[1] was valid to access before accessing it.
 
Just a fast note, since the main problem seems resolved: That's from TCEA 2008, which is in Texas.
ProCo 2009 is in its first year, but based on contests like TCEA (which is why we link to it for examples).
 
Back
Top