Home > front end >  Tolower Function does not work in c. I write TURAL muzafarov but it returns TURAL MUZAFAROV
Tolower Function does not work in c. I write TURAL muzafarov but it returns TURAL MUZAFAROV

Time:12-11

    char str[100];
    puts("Enter the string: ");
    // fgets(str, 100, stdin);
    gets(str);
    for (int i = 0; i < strlen(str); i  ) {
        if (isupper(str[i]) > 0) {
            str[i] = tolower(str[i]);
        }
        if (islower(str[i]) > 0) {
            str[i] = toupper(str[i]);
        }
    }
    printf("%s", str);

MY TOLOWER FUNCTION DOES NOT WORK FOR EXAMPLE MY INPUT IS: TURAL muzafarov but it returns TURAL MUZAFAROV

CodePudding user response:

OP's code errantly converts to lower and then back to upper

    if (isupper(str[i]) > 0) {
        str[i] = tolower(str[i]);
    }
    // All alpha are lower case at this point
    if (islower(str[i]) > 0) {
        str[i] = toupper(str[i]);
    }

Other issues

Wrong test

is...() returns zero or non-zero. Testing the sign bit is amiss. @Eric Postpischil

    // if (isupper(str[i]) > 0) {
    if (isupper(str[i])) {

Undefined behavior when str[i] < 0

Avoid that by accessing the string as unsigned char

Do not use gets()

It is no longer part of C. Why is the gets function so dangerous that it should not be used?

Avoid repeatedly calculating the string length

Simple test for the null character

// for (int i = 0; i < strlen(str); i  ) {
for (int i = 0; str[i]; i  ) {

Amended code with some other fixes too.

char str[100];
puts("Enter the string: ");
if (fgets(str, sizeof str, stdin)) {  // Test fgets result.
  unsigned char *ustr = (unsigned char *) str;
  for (size_t i = 0; ustr[i]; i  ) {  // Use size_t to handle even _long_ strings.
    if (isupper(ustr[i])) {
      ustr[i] = tolower(ustr[i]);
    } else if (islower(ustr[i])) {  // Notice the `else`
      ustr[i] = toupper(ustr[i]);
    }
  }
}
printf("%s", str);

CodePudding user response:

You are doing back 2 back two. operation. first you convert string to lowercase then you do uppercase conversion. please remove below code which converts string into uppercase.

if(islower(str[i])>0)
{
     str[i]=toupper(str[i]);
}

EDIT: C Reference says about toupper()

int toupper( int ch );

ch - character to be converted. If the value of ch is not representable as unsigned char and does not equal EOF, the behavior is undefined.

hence, below lines are not correct. the argument to toupper needs to be converted to unsigned char to avoid the risk of undefined behavior.

if (isupper(str[i]) > 0) {
    str[i] = tolower( str[i]);

change to

if(islower((unsigned char)str[i])>0)
{
     str[i]=toupper((unsigned char)str[i]);
}

also need to change below block of code

if (islower(str[i]) > 0) {
            str[i] = toupper(str[i]);

changed to

if (islower((unsigned char)str[i]) > 0) {
            str[i] = toupper((unsigned char)str[i]);

output:

Enter the string: 
TURAL muzafarov
tural muzafarov
  • Related