Home > database >  an if-body is never executed while checking if a character is lowercase, why?
an if-body is never executed while checking if a character is lowercase, why?

Time:07-16

I have a problem with this program

program takes strings from the command line, and it returns the same strings with capital letters at the end of each string, if possible, of course. (i.e if last letters are lowercase, and alphabetic)

for example, "32 hello world !" becomes "32 hellO worlD !"

this is my solution:

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char* argv[]) {
    if (argc == 1) {
        return 1; 
    }
    int j = 0; 
    for (int i = 0; i < argc; i  ) {
        j = strlen(argv[i]);
        if (isalpha(j) == 1) {
            if (islower(j) == 1) {
                argv[i][j] -= 32;
            }
        }
        j  ;
    }



    return 0; 
}

when debugging line-by-line, I've noticed that this this if-body is never executed, and I don't know why.

  if (islower(j) == 1) {
                argv[i][j] -= 32;
            }

CodePudding user response:

The isXXX() functions don't necessarily return 1 when the condition is true, they just return some non-zero value. So don't compare with a specific value, just test it as a boolean.

There's no need to test isalpha(), since islower() will only be true for alphabetic characters.

Another problem is that j is not a character in the string, it's the length of the string. You need to use that to index into the string. You have to subtract 1 since indexing goes from 0 to length-1.

You should use toupper() rather than subtracting 32, which is specific to ASCII. If you do this you don't even need to test islower(), since it returns the original value when the argument isn't uppercase; you only have to check that the string has at least 1 character.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char* argv[]) {
    if (argc == 1) {
        return 1; 
    }
    for (int i = 1; i < argc; i  ) {
        int j = strlen(argv[i]);
        if (j > 0) {
            argv[i][j-1] = toupper(argv[i][j-1]);
        }
    }

    return 0; 
}
  • Related