tolower

Hi, I have been fiddling with c++ and I can't figure out why I am getting the issue with this conversion function. I created a c-string and then copied each to the new array. However, when I display the result tolower works fine but I get a bunch of random symbols followed by the original c-string in upper case. Can someone explain what is happening here? the only thing I can think of at the moment is that somehow this is going beyond the bounds of the array...

int main() {

char big[] = "BIG";
char little[4];
cout << big << endl;

for (int i = 0; big[i] != '\0'; i++)
{
little[i] = tolower(big[i]);
}


cout << little << endl;

return 0;
}
You need to add the null terminator for little.

Either do
 
    little[3] = '\0';  // add null terminator 

or initialise it in the declaration,
 
    char little[4] = { 0 };

Awesome thank you! One more question, I'm assuming going forward that unless you initialize a character array as a c-string explicitly you must do this? This is a question in a text and it said to convert then to set it to the variable little. So because the little char array was not initialized it has no bearing as to whether its a character array or a c-string?
A c-string is an array of characters. But an array of characters isn't necessarily a c-string.

Usually a c-string will have two characteristics:
1. all the characters are valid and displayable - usually this means an ASCII character in the range 32 to 127.
2. After the last printable character there will be a null terminator (a byte with the value 0).

If the character array is not initialised, its contents are garbage (it could contain anything at all).

Often when working with c-strings and arrays, you might allocate a buffer of a size larger than is necessary, to allow for later changing the contents of the string. It isn't strictly necessary to initialise the entire array, as long as there is a valid c-string stored at the start of the array.

see tutorial:
http://www.cplusplus.com/doc/tutorial/ntcs/
Last edited on
Topic archived. No new replies allowed.