I would like to take a string input, convert them into either lowercase or uppercase and print them. So far, I have successfuly implemented that. Now, I want to modify my program such that if the input has whitespace in it, it will print all of the converted letter plus the whitespace
e.g.,
Enter a string: STACK OVERFLOW
Output: stack overflow
So here is my code:
#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
#include<string.h>
#define MAX_CHAR 50
char to_lowercase(char letter);
char to_uppercase(char letter);
int main(void)
{
char user_input[MAX_CHAR];
printf("Enter a string: ");
scanf("%s", &user_input);
for (int i = 0; i <= MAX_CHAR; i++)
{
if (user_input[i] == 0){exit(EXIT_SUCCESS);}
else{printf("%c", to_lowercase(user_input[i]));}
}
return EXIT_SUCCESS;
}
char to_lowercase(char letter)
{
if ((97 <= letter) && (letter <= 122)) {return letter;}
else if ((65 <= letter) && (letter <=90)) {return letter + 32;}
else if (letter == 32){return letter;}
else
{
printf("Not a valid character!");
exit(EXIT_FAILURE);
}
}
char to_uppercase(char letter)
{
if ((65 <= letter) && (letter <= 90)) {return letter;}
else if((97 <= letter) && (letter <= 122)) {return letter - 32;}
else if (letter == 32){return letter;}
else
{
printf("Not a valid character!");
exit(EXIT_FAILURE);
}
}
My current approach is to check using the ASCII code for whitespace (#32), however this doesn't really work because when i type "STACK OVERFLOW", the program will only print "s"
the program will only print "s"Dones't it print "stack"? It prints "stack" for me, not only "s".%sspecifier forscanfwill read a space delimited word. If you want to read a whole line usefgets.65is supposed to be the ASCII encoded value for the character'A'use the actual letter instead. Also note that ASCII is not mandated by the C specification, there are other encodings available still in use. That's why you really should be using the standardtoupperandtolowerfunctions instead of making your own.for (int i = 0; i <= MAX_CHAR; i++)can go out of bounds of the array. Change the condition toi < MAX_CHAR. But that will only protect you from going out of bounds, a better condition isuser_input[i] != '\0'. That will end the loop when you get to the string terminator, and you don't need the terminator check inside the loop itself.