Search code examples
c++characteroperation

Character string operation


In C++, what happens if I have

S[6] = "word";

and then I have:

S[x] - '0';

where x is 0 - 4 ... What does that line?


Solution

  • I suppose that your program is something like this:

    int main()
    {
      char S[6] = "word";
      for (int i=0; i < 4; i++)
        cout << S[i] - '0' << endl;
    }
    

    the first time S[i] - '0' calculates 'w' - '0', which are the ascii values of the characters ('w' == 119 and '0' == 48). So it results in 71.

    The whole output is:

    71
    63
    66
    52
    

    which is not really useful.

    S[i] + 'A' - 'a' would be useful. It will change the lower case characters to upper case (assuming that there are only lower chase characters in the string)