my god, the guy is just trying to get some string input tested and you're harassing him mercilessly and refusing to give any code like it's gold-plated or something.
now really, if you people are going to be such hardasses, then at least get your information correct: part of the problem that he's having -- and that you're allowing to perpetuate -- is that fgets() requires you to allocate your character array by at least TWO (2) chars larger than your largest possible input, because it collects the newline ('\n') character in addition to appending the null character ('\0').
if you're going to collect input from a user via the standard input (terminal) then you better really oversize the character buffer, unless you're prepared to develop some bulletproof error testing and input buffer overflow controls. but we're not going to go there, so for now just do it like this:
Code:
char c[500]; // yes, that's right. memory is cheap.
while (fgets(c, sizeof c, stdin) != NULL) // no magic numbers here
{
checkstring(c);
}
Originally Posted by
fxtdr79
What I'm saying is if I type 123456789lb shouldn't c be c = {1, 2, 3, 4, \n} so when I call checkString, it shouldn't be able to find the string "lb"?
not necessarily. when you overflow your array, the behavior is undefined. depending on your system/compiler it may "work" one way or "not work" in another. looks like in this case, your overflowed char array didnt crash into anything else, so it "works". try initializing another variable before or after that array and it probably won't.
BTW, have you considered using "strtol"? this will convert the numeric string to a (long) integer, and give back a pointer to the rest of the string. it might be a bit more useful for what you're trying to accomplish, overall. here's a lazy example that employs no error checking, just to give you an idea:
Code:
char str[20] = "12345 lbs"; // notice it's "lbs" and not "lb"
char *ptr;
long value;
value = strtol(str, &ptr, 10) // 10 is the base to convert, i.e. decimal base 10
while(*ptr = ' ') // is current single pointer character a space?
ptr++; // increment until it's not
if (strncmp(ptr, "lb", 2)) // using 'strncmp' just for the hell of it. only looks at 2 characters
printf ('%ld pounds.\n", value);
else if (strncmp(ptr, "kg", 2))
printf ("%ld kilograms\n", value);
else
printf ("%ld [unknown units]\n", value);