asciictypetolowertoupper

Converting lower/upper case letters without ctype.h


I just saw that this could technically work, the only mistake I couldn´t resolve was the last ASCII character that gets printed everytime I test it out, I also tested this out without using the name variable, I mean just making a substraction of 32 to any lower case letter in ASCII should give me their upper case one and it does, but I´m curious on why I´m getting an additional char, wich from what I see in screen is apparently Û.

#include <stdio.h>
 main()
{
char name[22];
int i;

fputs("Type your name ",stdout);
fgets(name,22,stdin);


for (i = 0; name[i] != '\0'; i = i + 1)
printf("%c",(name[i])-32);  /*This will convert lower case to upper */
                            /* using as reference the ASCII table*/   
fflush(stdin);
getchar();
} 

Solution

  • Perhaps there is a line break character at the end of the string.

    You can check the chararacter code, so that you only convert characters that actually are lower case letters:

    for (i = 0; name[i] != '\0'; i = i + 1) {
      char c = name[i];
      if (c => 97 && c <= 122) {
        c -= 32;
      }
      printf("%c", c);
    }