Thanks. This is a very interesting article. Seems a lot of on line sample codes related to char* manipulation are not right (even if it happen to work in certain compilers).
For example,
http://www.cprogramming.com/faq/cgi-bin/smartfaq.cgi?answer=1046053421&id=1043284392
I will get running error for 1, but not 2. As all operations are trying to modify to char*, should both 1 and 2 have probelm in running?
Saw another implementation for toupper in string as in 3. Seems a safe way is always to convert char* to string before any manipulation/chagnes, right?
Thanks
/*
* A C++ Version showing how to iterate an array, converting character case
*/
#include <cctype>
#include <iostream>
using std::cout;
using std::endl;
int main(void)
{
char hello[] = "Hello World";
cout << "Before conversion: " << hello << endl;
for (char *iter = hello; *iter != '\0'; ++iter)
{
*iter = std::tolower(*iter);
++iter;
}
cout << "After conversion: " << hello << endl;
return 0;
}
/*
Output:
Before conversion: Hello World
After conversion: hello world
*/
2.
/*
* A short function to convert an array to uppercase,
* showing that we don't need to worry about non-character
* elements.
*/
#include <stdio.h>
#include <ctype.h>
void upstr(char *s)
{
char *p;
for (p = s; *p != '\0'; p++)
*p = (char) toupper(*p);
}
int main(void)
{
char mystring[] = "Some 1234 text 5678 here!";
puts(mystring);
upstr(mystring);
puts(mystring);
return(0);
}
/*
* Program output:
Some 1234 text 5678 here!
SOME 1234 TEXT 5678 HERE!
*
*/
3.
std::string data = "Abc";
std::transform(data.begin(), data.end(),
data.begin(), ::toupper);
cout << data << endl;