<$BlogRSDUrl$>

Wednesday, May 19, 2004

Hoping someone can help me with what is probably a silly question. I am to take user input, put it into uppercase, then lowercase. The code below does output the uppercase, except I am missing the first character. I don't get any output for the lowercase.

Thanks in advance..any help is appreciated!



#include
#include


void main (void)

{

char text[70];

char *text_ptr=text;

int i;


printf ("\nEnter a line of text (up to 69 [COLOR=blue]characters):\n");

gets(text);


text[70]='\0';>



printf("\nThe line of text in uppercase [COLOR=blue]is:\n\n");

i=0;

while(*text_ptr)

{
*text_ptr++;

putchar(toupper(*text_ptr));

}

printf("\n\nThe line of text in lowercase is:\n\n");

i=0;

while(*text_ptr)

{

*text_ptr++;

putchar(tolower(*text_ptr));

}

}

--------------------------------------------------------------------------------

Become A Member, Free!
Character Array and Pointer
Scorpions4ever
For printing in uppercase, flip the order of the two statements in the loop, (i.e.) uppercasing the pointer and then increment it. You're incrementing the pointer first and then uppercasing, which is why you're missing the first char:

while(*text_ptr)
{
putchar(toupper(*text_ptr));
text_ptr++;
}

As for the lowercasing part, you forgot to reset your pointer to the beginning of the string again. As before, also change the order of your statements inside the loop and you should be good to go.

printf("\n\nThe line of text in lowercase is:\n\n");
text_ptr = text; /* <--- Point text_ptr to the beginning of the string again */
while(*text_ptr)
{
putchar(tolower(*text_ptr));
text_ptr++;
}


I realize that you're probably a beginner to C programming, so I'll give you a little friendly advice. Using gets() is highly discouraged for any serious programming. Consider using fgets() or fread() instead. See the BUGS section in http://www.openbsd.org/cgi-bin/man.cgi?query=gets&apropos=0&sektion=0&manpath=OpenBSD+Current&arch=i386&format=html for why

This page is powered by Blogger. Isn't yours?