home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 32,152 of 33,346   
   =?ISO-8859-1?Q?Daniel_Kr=FCgler?= to All   
   Re: why can't i access std::string with    
   16 Apr 12 23:35:13   
   
   From: daniel.kruegler@googlemail.com   
      
   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    
   > #include    
   >   
   > 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   
      
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca