Is there a good example of how toupper() works?

Avery Colter avery at netcom.UUCP
Fri Oct 26 17:15:32 AEST 1990


comp.lang.c/16831, edh at ux.acs.umn.edu

> Basically, what I want to do is take a string of upper/lower case, and make
> it all upper case.  Here is a first try at it,


> #include <ctype.h>
> main()
> {
> 	char *duh = "Hello";
> 	printf("%s\n", duh);
> 	while (*duh <= strlen(duh)) {

a) You should #include <string.h> if you're going to use strlen.

b) (*duh <= strlen (duh)) is a type mismatch. strlen returns an
integer, while *duh is a character. And even with typecasting,
as some others have said it is not a good condition.

Better to do something like:

while (*duh != NULL)

Then you don't need to use #strlen or include <string.h>.
You can do this for one simple reason, at least with the
compiler I use: the value strlen returns is the number of
characters BEFORE THE TERMINATING NULL CHARACTER!	
>	if (islower(*duh)) *duh = toupper(*duh);
>	*duh++;

You gottit backwards, and dereferenced:

++duh; is what you want.

>	}
>	printf("%s\n", duh);
> }

> And what I get is :

> Hello
> Hello

Small wonder: that while condition, even if it gets automatically
typecasted, is comparing the ASCII value of 'H' to the length of
the string, which is 5.

Just make the while condition that the terminating NULL character
of the string has been reached.


-- 
Avery Ray Colter    {apple|claris}!netcom!avery  {decwrl|mips|sgi}!btr!elfcat
(415) 839-4567   "Fat and steel: two mortal enemies locked in deadly combat."
                                     - "The Bending of the Bars", A. R. Colter



More information about the Comp.lang.c mailing list