PPJack
PPJack

Reputation: 93

two functions to transfer characters in string to uppercase. one works the other fails to work. why?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SIZE 73
void tobigletter(char *p);
int main(void)
{
    char ch1[SIZE];
    puts("Enter a string");
    gets(ch1);
    tobigletter(ch1);
    printf("ch1 = %s\n" , ch1);
    system("pause");
    return 0;
}
void tobigletter(char *p)
{
    while(*p)
    {
        if(islower(*p))
            *p -= 32;
        p++;
    }
}

Look at the code above. The function tobigletter is used to transfer whatever is lowercase letter into capital letters. It works fine. Now I have written another function. I have no idea why it doesn't work.

void tobigletter(char *p)
{
    int i;
    for(i = 0 ; i < strlen(p) ; i++)
        if(islower(*(p + i))
            *p -= 32;
}

Upvotes: 0

Views: 47

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

Write

 if(islower(*(p + i))
            *( p + i ) -= 32;
              ^^^^^^

But in any case it is better to use standard function toupper instead of the magic number 32.

For example

 if ( islower( ( unsigned char )*( p + i ) ) 
     *( p + i ) = toupper( ( unsigned char )*( p + i ) );

Upvotes: 4

Related Questions