I have this code that will take the cstring from the user. Total limit inside the cstring would be 10 including the null character. I'm trying to convert the user input string to all uppercase letters. Unfortunately, I m not able to do so and i'm getting a silly output like this. I type in hello there. cstring stores in hello ther. and then this is the output
hello ther7269767932.......
1 2 3 4 5 6 7 8 9 10 11 12 13 14
char cstring[10];
cout<<"\n\tType in a string: ";
cin.get(cstring,11);
cout<<"\n\n\t" <<cstring;
int index=0;
char ch=0;
for(index=0;index<10;index++)
{
ch=cstring[index];
cout<<toupper(ch);
}
Also, May I know what this function is doing? I just read the book and realized that toupper will return an int value. I would like to know what this function is doing, but would also like receiving an hint please :0
Oh and booradely, as far as I know and have heard the extra 11 is used on c strings because of the null character. If I have ten in the character array, it will store only 9, that's why I have 11 on the get function so it can discard the null.
What I'm saying is that you don't want to discard the null. The way c-strings are usually interpreted is that they go on until the null terminator is detected. Since there isn't such a character stored in your array, it keeps right on printing garbage after the contents of the array are exhausted.
EDIT: toupper(ch) returns an int, so you would have to perform some sort of conversion (like tom221b did by adding char) so that cout's << operator prints the character instead of its integer equivalent.
Was checking my code out and I figured out what you were saying. I get the results I want when I enter in the characters more then 10. If I enter in less then 10, I get garbage out of it. How can I not discard the null in my case?
Apologize for asking to many questions. Fyi, this is not my homework and i'm not looking forward to get answers from here. Same code. I was just practicing converting the string to uppercase. I'm not to the uppercase part yet, but for the second part of my code. String variable. It doesn't let the user input a name.In fact, it just scrolls doing to, the name is...
I thought you were giving me an idea :D Unforunately,i can't see where your terminating the null character in your for loop. It looks identical to my other previous code...
for (int index=0; char ch=cstring[index]; index++)
{
cout<<(char)toupper(ch);
}
the for loop will execute so long as the condition is true.
What is the condition? char ch=cstring[index]
Here the character cstring[index] is assigned to the variable ch.
Then the resulting value is evaluated as a boolean (true or false) value. Any non-zero value (such as a letter of the alphabet) gives true and a zero byte will give false. Thus the body of the loop is executed only for the actual text of the string.