Re: Problem with <algorithm> transform
* Erik WikstrFm:
On 2008-01-06 21:45, Andrew Koenig wrote:
transform(s.begin(), s.end(),s.begin(), toupper);
Something seems seriously wrong but I can't figure it.
Alas, toupper is a macro so you can't pass it as an argument.
Are you sure? In C99 it is a function specified as int toupper(int c)
(section 7.4.2.2, "The toupper function") and in C++98 table 45 it is
also listed as a function.
The reference you give is correct, and means that Andrew Koenig made a
mistake.
To the OP: the code you posted compiled and ran fine with MSVC++ so I am
not sure why it did not work for you.
Ironically, the error seems to be due to Koenig lookup... :-)
However, adding an include of <locale> does not reproduce the error with
MSVC 7.1.
As Newton puportedly said, I frame no hypothesis.
However there is also a toupper()
function in C++ declared in the <locale> header which might work (i.e.
replace <cctype> with <locale> and try again).
No, that one is a bit different: it suffers from the usual standard
library (except STL parts) unusability and complexity, taking a locale
argument as second argument.
A cure for the immediate problem is to write
::toupper
but this may be a compiler-specific cure (I'm not sure).
However, it doesn't matter much, because using the C library's toupper
function directly is a big no-no: it should only be used via a wrapper like
char toUpper( char c )
{
return static_cast<char>(
::toupper( static_cast<unsigned char>( c ) )
);
}
Otherwise, with negative char value promotion to integer (the formal
argument) will yield a value that is not representable as unsigned char,
which the C library toupper function requires.
So to sum up, the Josuttis book example may be correct for the given
data (only ASCII characters), but not for an arbitrary input string,
and, g++ apparently does something funny.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?