2

The below code snippet is used to convert a string to lower case.

int main()
{
    unsigned char s[] = "AbS.d_";

    tolower(s);
    printf("%s\n", s);

    return 0;
}

I am getting the output as:

AbS.d_

Why the string is not being converted?

Green goblin
  • 9,898
  • 13
  • 71
  • 100
  • Because [tolower()](http://www.cplusplus.com/reference/clibrary/cctype/tolower/) works character-by-character, and returns an *output*. It doesn't convert the whole string at once. And even if it did, it would cause an access violation on your static string ;) – paulsm4 Aug 27 '12 at 16:06
  • 1
    @paulsm4 The string is not static (maybe the question was edited?) – Praetorian Aug 27 '12 at 16:08
  • @MatteoItalia, Indeed [it does](http://ideone.com/htlXf). The function takes an `int`, and you pass a pointer. – chris Aug 27 '12 at 16:11
  • 2
    @chris I see your link and raise you [this one](http://liveworkspace.org/code/21386e9cba33a6b3fe603a3b2d016393). – Luc Danton Aug 27 '12 at 16:14
  • @chris: you are right, I tend to forget how forgiving is C in respect to C++. – Matteo Italia Aug 27 '12 at 16:15
  • @LucDanton, I agree. Warnings would have maybe saved the OP's question. – chris Aug 27 '12 at 16:16
  • @paulsm4: The documentation you cite doesn’t mention a critical point: when you pass a `char` argument, it must be cast to `unsigned char`, not to `int`. See http://pubs.opengroup.org/onlinepubs/9699919799/functions/tolower.html for a better source. – Roland Illig Jan 03 '15 at 16:06

2 Answers2

5

tolower takes a character type as parameter, but you use a string. You need to run through your array, and call tolower for each character.

md5
  • 23,373
  • 3
  • 44
  • 93
5

tolower takes int and return lowered int.

This should work:

int i=0;
for(i=0; s[i]; i++)
{
    s[i]=tolower(s[i]);
}
Rohan
  • 52,392
  • 12
  • 90
  • 87