#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Posts
    7
    Rep Power
    0

    Question Character Array and Pointer


    Hi All...

    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 <stdio.h>
    #include <ctype.h>


    void main (void)

    {

    char text[70];

    char *text_ptr=text;

    int i;


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

    gets(text);


    text[70]='\0';>



    [COLOR=blue] printf("\nThe line of text in uppercase 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));

    }

    }
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,593
    Rep Power
    4207
    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:
    Code:
    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.
    Code:
    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.c...86&format=html for why.
    Last edited by Scorpions4ever; April 13th, 2003 at 05:11 PM.
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Posts
    7
    Rep Power
    0

    Thumbs up


    Thanks for your help. Yes, I am new to programming. I hate to be so obvious! Thanks for the tip, I appreciate it.

    Kathy

IMN logo majestic logo threadwatch logo seochat tools logo