My problem this week is to manipulate char arrays using C-style, I have been struggling all day with this one. Basically what we have to do is design a program to take a string less than 11 chars, with no spaces, and convert all lower case to upper. I plan on doing this with these 3 items, 1 array, 1 global int, and 1 function:
char STRING[11];
int count;
void cStringToUpper(int count);
within the function, I have gotten this far with changing from lower to upper case. I have an if that asks if the char entered is even lowercase then I subtract 32 from the int value of that char. At this point I do not know how to bring my new value back to a char within the string.
void cStringToUpper(int count)
{ // opening for to upper
if (97 >= static_cast<int>(STRING[count]) <= 122)
{ // opening if it is lowercase, then subtract 32 to make uppercase
int change;
change = static_cast<int>(STRING[count]) - 32;
static_cast<int>(STRING[count]) = change;
} // closing if
return;
The static_cast will not allow me to change the value. Also I have realized during this message i need to modify my if to (static_cast<int>(STRING[count]) >= 97 && static_cast<int>(STRING[count]) <= 122)
You don't need that static cast. Casting from char to int is implicit. Though there is no reason to use ints at all. Consider this code to convert a single char ch to uppercase: if(ch >= 'a' && ch <= 'z') ch = ch - 'a' + 'A';. A lot more readable.
Another problem with your code is that it only treats one letter.
What you need is to put the code for a single char into a for loop from 0 to count.
I was trying to save space and left that for statement out, it is there. I actually got this to work with the static_cast but will try it out your way, much simpler.
However I now have another problem, while asking the user if they want to try again I can not clear the buffer to allow them to input again. Meaning I have this code to ask if they want to enter another string, all inside a do/ while:
cout << "Press any key to try again or Q to quit: ";
cin >> AGAIN;
AGAIN = toupper(AGAIN);
}
while (AGAIN != 'Q');
For whatever reason the program is not restarting at do until a char is entered and the enter key pushed. Then what ever is entered becomes the input for STRING. I can not get the buffer to clear after asking for the user to press any key.
cin.ignore(numeric_limits<streamsize>::max(), '\n'); will clear the input buffer, if I recall correctly.. you need to include <limits> for numeric_limits, but any big number (bigger than the number of char you need to discard) would work fine.