Am 17.04.2012 00:09, schrieb
news.eternal-september.org:
> Hello,
>
> I'd like to access C++ strings the way i did in C , that is:
> char foo[]="foo"; //foo[0] foo[1] ...
>
> I read several times that [] was allowed for string access.
It is allowed, see 21.4 [basic.string]:
// 21.4.5, element access:
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
Note that (const_)reference are just alias for a reference to char
(const).
> Unfortunately, i think i'm missing something.
>
> #include <string>
> #include <iostream>
>
> using std::string;
>
> int main(void)
> {
> string foo="foo";
> string bar="bar";
>
> string result = "and ? ";
> result += foo[1] + bar[2];
Nice "gotcha" example for operator overloading: The language is
designed such to allow extending it, but not changing it. Note that
the expressions foo[1] and bar[2] just have type char, so before the
compound assignment operator += takes action, we simply have the
effect of adding the values of two chars. The result is the ordinal
value of adding 'o' and 'r'. The character value of this sum will then
be added as trailing new character to the string "and ? "
The right fix in this example is to split the assignment into two
steps:
result += foo[1];
result += bar[2];
HTH & Greetings from Bremen,
Daniel Krügler