This is a program for converting lower case letters in a string to upper case and vice versa in C language.
In this code I am trying to take input string str from user using fgets() function but it is not working. I even tried using gets() but it is also not working.
It skips taking input and execute the program.
What can I do?
I tried using for loop but it is not terminating on new line.
Can I do it with any function or using any loop?
#include <stdio.h>
#include <string.h>
char lower(char *str);
char upper(char *str);
int main() {
char *newstr;
char ans;
printf("Enter U for Lower case -> Upper case\nEnter L for Upper case -> Lower case:\n");
scanf("%c", &ans);
char str[100];
printf("Enter the string:\n");
fgets(str, 100, stdin);
if (ans == 'U' || ans == 'u') {
// newstr = upper(str);
upper(str);
}
else if(ans == 'L' || ans == 'l') {
// newstr = lower(str);
lower(str);
}
else {
printf("Try entering a valid input.");
}
// printf("%s", newstr);
printf("%s", str);
return 0;
}
char lower(char *str) {
for (int i = 0; i < (strlen(str)); i++) {
char c[] = { str[i], '\0' };
if (strstr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", c)) {
str[i] = str[i] - 32;
}
}
// return str;
}
char upper(char *str) {
for (int i = 0; i < (strlen(str)); i++) {
char c[] = { str[i], '\0' };
if (strstr("abcdefghijklmnopqrstuvwxyz", c)) {
str[i] = str[i] + 32;
}
}
// return str;
}
Answer: the
scanf()statement is leaving a newline character in the input buffer, which is causingfgets()to take it as an input and end the string.You can modify your code and move the
fgets()logic before thescanfstatement to make it work. Additionally, if conditions can be modified a little bit to make it better using ASCII values. Below is an example of working code: