<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>stdstring &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/stdstring/</link>
	<description>Feed of posts on WordPress.com tagged "stdstring"</description>
	<pubDate>Mon, 07 Dec 2009 23:36:21 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[switch-case and short std::strings]]></title>
<link>http://rthghts.wordpress.com/2009/07/06/switch-case-and-short-stdstrings/</link>
<pubDate>Mon, 06 Jul 2009 16:55:37 +0000</pubDate>
<dc:creator>Jani</dc:creator>
<guid>http://rthghts.wordpress.com/2009/07/06/switch-case-and-short-stdstrings/</guid>
<description><![CDATA[Parsing a file you might need a switch-case with short strings, two to four letters on 32-bit system]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Parsing a file you might need a <em>switch-case</em> with short strings, two to four letters on 32-bit systems, or even upto 8 letters on 64-bit. Using <em>if</em> would work, but looks ugly. Consider this:</p>
<pre>std::string s("AACE");

if( s[0] == 'A' ) {
  if( s[1] == 'A' )
    ...
  else if( s[1] == 'C' )
    ...
  ...
} else if( s[0] == 'B' ) {
  ...
}</pre>
<p>It gets ugly, doesn&#8217;t it?</p>
<p>A better solution, which shouldn&#8217;t harm endianness as long as it&#8217;s done on a single computer or the computers communicating use the same endianness:</p>
<pre>enum
{
  AA = 'A'*0xFF+'A',
  AC = 'A'*0xFF+'C'
};

std::string s("AACE");
switch( s[0]*0xFF+s[1] )
{
  case AA:
    break;
  case AC:
    break;

  default:
    break;
}</pre>
<p>You could write a macro to define the enums and doing this would be easier that way.. Also, you must make sure that the string is long enough!</p>
<p>I was told that the only case it wouldn&#8217;t work is when byte isn&#8217;t eight bits. I doubt it I&#8217;ll be running my code on a machine where byte isn&#8217;t eight bits&#8230;</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[std::string caveat]]></title>
<link>http://nibuthomas.com/2009/05/18/stdstring-caveat/</link>
<pubDate>Mon, 18 May 2009 12:18:16 +0000</pubDate>
<dc:creator>Nibu Thomas</dc:creator>
<guid>http://nibuthomas.com/2009/05/18/stdstring-caveat/</guid>
<description><![CDATA[Never access an std::string&#8217;s buffer with an intent to increase/decrease it&#8217;s length nor]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Never access an <em>std::string</em>&#8217;s buffer with an intent to increase/decrease it&#8217;s length nor pass such a buffer to functions which takes a char*. I did this mistake sometime back and got trapped in a strange bug with operator +=. This is how my code looked.</p>
<pre class="brush: cpp;">std::string str( ' ', MAX_PATH );
GetFolderName( pFullPath, &amp;str[0] ); // Oop</pre>
<p>Problem with above code is that you won&#8217;t get an immediate crash since it&#8217;s a properly allocated buffer with <em>MAX_PATH</em> chars. But if you do further operations on such string expect plenty of inconsistencies. This is how my code looked after above piece of code&#8230;</p>
<pre class="brush: cpp;">str += &quot;\\&quot;; // Append backslash</pre>
<p>I was expecting a valid path with backslash appended towards it&#8217;s end, but this never happened and debugging with debugger too didn&#8217;t help.</p>
<p>So now let me tell you what the exact problem is! When you do <em>&#38;str[0]</em> you pass the address to the first char in <em>std::string</em>&#8217;s buffer. So when function <em>GetFolderName</em> fills in this buffer with folder path the length of std::string is not updated since it&#8217;s a C style function and it&#8217;s neither expected to do so. So the function terminates given buffer with a &#8221; with <em>std::string</em>&#8217;s length way high (<em>MAX_PATH</em>). So now when I do a += std::string internally fails some condition leading to unexpected results, note that this piece of code never caused a crash but I was quite lucky and watchful enough to fix this stupid bug. Sigh!</p>
<p>So watchout, there is no <em>CString::GetBuffer</em> or <em>CString::GetBufferSetLength</em> type of function for <em>std::string</em>, well at least for now.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Como converter um número para uma std::string e vice-versa]]></title>
<link>http://murilo.wordpress.com/2008/10/01/converter-std-string-para-numero-e-vice-versa/</link>
<pubDate>Wed, 01 Oct 2008 03:41:05 +0000</pubDate>
<dc:creator>Murilo Adriano</dc:creator>
<guid>http://murilo.wordpress.com/2008/10/01/converter-std-string-para-numero-e-vice-versa/</guid>
<description><![CDATA[Que a biblioteca &lt;iostream&gt; oferece inúmeras facilidades para manipular I/O nós já sabemos mas]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><pre><img class="alignright" style="border:0;background:none;" title="C++" src="http://murilo.wordpress.com/files/2008/10/cpp.png" border="0" alt="" width="120" height="107" /></pre>
<p>Que a biblioteca <code>&#60;iostream&#62;</code> oferece inúmeras facilidades para manipular <code>I/O</code> nós já sabemos mas, como converter um valor para uma <code>std::string</code>?</p>
<p>A bliblioteca <code>&#60;iostream&#62;</code> nos permite converter facilmente qualquer coisa para uma <code>std::string</code> usando a seguinte sintaxe (o exemplo a seguir converte um <code>double</code>, mas você pode substituir por qualquer coisa imprimível usando o operador &#60;&#60;):<!--more--></p>
<pre>#include &#60;iostream&#62;
#include &#60;sstream&#62;
#include &#60;string&#62;

std::string stringalizar(double x)
{
    std::ostringstream oss;
    oss &#60;&#60; x;
    return oss.str();
} 

int main()
{
    std::string str;
    double dbl = -2.00655;

    str = stringalizar(dbl);

    std::cout &#60;&#60; str &#60;&#60; std::endl;
}</pre>
<p>↓</p>
<p>O tipo <code>std::ostringstream</code> oferece facilidades de formatação assim como aquelas do <code>std::cout</code>. Nós podemos usar manipuladores e <em>flags</em> de formatação para controlar o formato do resultado, assim como podemos fazer com o <code>std::cout</code>.</p>
<p>Nesse exemplo, inserí <code>x</code> em <code>oss</code> pelo operador sobrecarregado de inserção &#60;&#60;. Isso invoca as facilidades do <code>&#60;iostream&#62;</code> para converter <code>x</code> em uma <code>std::string</code>.</p>
<p>A expressão <code>oss.str()</code> retorna uma <code>std::string</code> que contem o que foi inserido na <em>stream</em> <code>oss</code>, nesse caso, uma <em>string</em> com o valor de <code>x</code>.</p>
<h3>Agora contrariando, ou fazendo o contrário <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </h3>
<pre>#include &#60;iostream&#62;
#include &#60;sstream&#62;
#include &#60;string&#62;

double converterParaDouble(std::string str)
{
    std::istringstream iss(str);
    double retorno;
    iss &#62;&#62; retorno;
    return retorno;
} 

int main()
{
    std::string str("261.15");
    double dbl = converterParaDouble(str);
    std::cout &#60;&#60; dbl &#60;&#60; std::endl;
}</pre>
<p>↓<br />
O tipo <tt>std::istringstream</tt> oferece facilidades de formatação assim como aquelas que <tt>std::cin</tt> oferece. Podemos usar modificadores e flags de formatação assim como em <tt>std::cin</tt>.</p>
<p>Nesse exemplo, nós inicializamos a <code>std::string str</code> com &#8220;261.15&#8243; e passamos para nossa função de conversão. Na função nós inicializamos a <code>std::istringstream iss</code> passando a <code>std::string str</code>, então nós extraímos <code>iss</code> para retorno com o operador de extração &#62;&#62;. Isso nos provê as facilidades da <code>&#60;iostream&#62;</code> para converter a nossa <code>string</code> apropriadamente baseando-se no tipo da variável retorno.</p>
<p>Baseado em <a href="http://http://www.parashift.com/c++-faq-lite/index.html">http://www.parashift.com/c++-faq-lite/index.html</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[How to trim white space before and after a string?]]></title>
<link>http://nibuthomas.com/2008/09/05/how-to-trim-white-space-before-and-after-a-string/</link>
<pubDate>Fri, 05 Sep 2008 07:54:00 +0000</pubDate>
<dc:creator>Nibu Thomas</dc:creator>
<guid>http://nibuthomas.com/2008/09/05/how-to-trim-white-space-before-and-after-a-string/</guid>
<description><![CDATA[I will describe in this post three ways to trim a string of given characters&#8230; Using custom fun]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I will describe in this post three ways to trim a string of given characters&#8230;</p>
<ol>
<li>Using custom function for std::string</li>
<li>Using CString</li>
<li>Using StrTrim shell API function.</li>
</ol>
<p><strong>Using custom function for std::string</strong></p>
<p>Its bit strange that std::string doesn&#8217;t provide a Trim function <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_confused.gif' alt=':?' class='wp-smiley' />  , but hey since we&#8217;ve got head upon our shoulders we&#8217;re gonna write one. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> . Here is a simple function which removes white space before and after a string. We&#8217;ll call it Trim! <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<pre class="brush: cpp;">void Trim( const std::string&amp; StrToTrim, std::string&amp; TrimmedString )
{
  // Find first non whitespace char in StrToTrim
  std::string::size_type First = StrToTrim.find_first_not_of( ' ' );
  // Check whether something went wrong?
  if( First == std::string::npos )
  {
    First = 0;
  }

  // Find last non whitespace char from StrToTrim
  std::string::size_type Last = StrToTrim.find_last_not_of( ' ' );
  // If something didn't go wrong, Last will be recomputed to get real length of substring
  if( Last != std::string::npos )
  {
    Last = ( Last + 1 ) - First;
  }

  // Copy such a string to TrimmedString
  TrimmedString = StrToTrim.substr( First, Last );
}

int main()
{
  std::string StrToTrim = &quot; 32 Nibu babu thomas 2342 2 23 3 &quot;;
  std::string TrimmedString = &quot;On return will hold trimmed string&quot;;
  Trim( StrToTrim, TrimmedString );

  return 0;
}
//Output is: 32 Nibu babu thomas 2342 2 23 3</pre>
<p><strong>Using CString</strong></p>
<p>Also CString has a Trim function, if you have the liberty to use CString then that&#8217;s another option.</p>
<p><strong>Using StrTrim shell API function</strong></p>
<p>Another option is to use StrTrim shell API function. Here is a demo from MSDN.</p>
<pre class="brush: cpp;">#include &lt;windows .h&gt;
#include &lt;iostream .h&gt;
#include &quot;Shlwapi.h&quot; 

void main(void)
{
  //String one
  TCHAR buffer[ ] = TEXT(&quot;_!ABCDEFG#&quot;);
  TCHAR trim[ ] = TEXT(&quot;#A!_&quot;); 

  cout &lt;&lt; &quot;The string before calling StrTrim: &quot;;
  cout &lt;&lt; buffer;
  cout &lt;&lt; &quot;\n&quot;; 

  StrTrim(buffer, trim); 

  cout &lt;&lt; &quot;The string after calling StrTrim: &quot;;
  cout &lt;&lt; buffer;
  cout &lt;&lt; &quot;\n&quot;;
} 

OUTPUT:
- - - - - -
The string before calling StrTrim: _!ABCDEFG#
The string after calling StrTrim: BCDEFG</pre>
<p></iostream></windows></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[A TCHAR version of std stream and string classes]]></title>
<link>http://nibuthomas.com/2008/06/25/a-tchar-version-of-std-stream-and-string-classes/</link>
<pubDate>Wed, 25 Jun 2008 05:10:25 +0000</pubDate>
<dc:creator>Nibu Thomas</dc:creator>
<guid>http://nibuthomas.com/2008/06/25/a-tchar-version-of-std-stream-and-string-classes/</guid>
<description><![CDATA[Quite simple&#8230; // A TCHAR based std::string typedef std::basic_string&lt;tchar&gt; tstring; // ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Quite simple&#8230;</p>
<pre class="brush: cpp;">// A TCHAR based std::string
typedef std::basic_string&lt;tchar&gt; tstring;
// A TCHAR based std::ifstream;
typedef std::basic_ifstream&lt;/tchar&gt;&lt;tchar , std::char_traits&lt;TCHAR&gt; &gt; tstream;
// A TCHAR based std::stringstream
typedef std::basic_stringstream&lt;/tchar&gt;&lt;tchar , std::char_traits&lt;TCHAR&gt;, std::allocator&lt;/tchar&gt;&lt;tchar&gt; &gt; tstringstream;</pre>
<p>So now no need to worry about <em>UNICODE</em> and <em>ANSI</em>, should work as <em>CString</em>, since <em>TCHAR </em>becomes <em>char/wchar_t</em> based on _<em>UNICODE</em> macro definition.</p>
<p>Also note that stl has provided <em>UNICODE</em> versions of these classes for e.g. <em>wstring</em>, <em>wstringstream, wifstream</em>, but since windows has a type that switches automagically between <em>char/wchar_t</em>, we are making use of it.</p>
<p>So the idea behind this is that stl classes are mostly template based, so this means you can add your own version of an stl class for a custom type just like I&#8217;ve done. As a conclusion we can say that <em>std::string</em> can be called a<em> vector&#60;char&#62;</em> but with dedicated string operations.</tchar></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[C++: hash_set, hash_map]]></title>
<link>http://codare.net/2008/06/12/cpp-hash_set-hash_map/</link>
<pubDate>Thu, 12 Jun 2008 03:00:58 +0000</pubDate>
<dc:creator>Alfredo Kojima</dc:creator>
<guid>http://codare.net/2008/06/12/cpp-hash_set-hash_map/</guid>
<description><![CDATA[Apesar dos templates para hash_set e hash_map não serem padronizados, ambos são relativamente comuns]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Apesar dos templates para <code>hash_set</code> e <code>hash_map</code> não serem padronizados, ambos são relativamente comuns, estando disponíveis tanto na implementação GNU (ie, no GCC) quanto no Visual C++ no Windows. Existem algumas diferenças, como o <i>namespace</i> um pouco mais escondido no GNUC (<code>__gnu_cxx</code> <i>vs</i> <code>stdext</code>) e alguns métodos que existem em um mas não em outro (p.ex.: <code>reverse_iterator</code> que não existe no GCC); mas a maioria das vezes servem para o serviço.</p>
<p>Um problema comum com essas classes no GCC é um erro meio criptico quando tentamos usar <code>__gnu_cxx::hash_set&#60;std::string&#62;</code> ou <code>__gnu_cxx::hash_map&#60;std::string&#62;</code>:<br />
<code><br />
/usr/include/c++/4.2/ext/hashtable.h:595: error: no match for call to '(const __gnu_cxx::hash&#60;std::basic_string&#60;char, std::char_traits, std::allocator &#62; &#62;) (const std::basic_string&#60;char, std::char_traits, std::allocator &#62;&#38;)'<br />
</code></p>
<p>Este erro ocorre porque a libstdc++ não define uma função de hash para <code>std::string</code>. A solução é definir uma (O RLY?). Felizmente a biblioteca padrão define uma função de hash para strings do tipo <code>char*</code>, então podemos aproveitá-la:</p>
<pre>
struct string_hash : public std::unary_function&#60;std::string,size_t&#62;
{
&#160;&#160;size_t operator() (const std::string &#38;v) const
&#160;&#160;{
&#160;&#160;&#160;&#160;return __gnu_cxx::hash()(v.c_str());
&#160;&#160;}
};
typedef __gnu_cxx::hash_set&#60;std::string,string_hash&#62; string_hash_set;
</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[generic stringstream function in c++]]></title>
<link>http://pbeblog.wordpress.com/2008/02/09/generic-stringstream-function-in-c/</link>
<pubDate>Sat, 09 Feb 2008 11:06:57 +0000</pubDate>
<dc:creator>Patrick</dc:creator>
<guid>http://pbeblog.wordpress.com/2008/02/09/generic-stringstream-function-in-c/</guid>
<description><![CDATA[Something i&#8217;ve found useful while programming in C++, is the use of std::stringstream to conve]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Something i&#8217;ve found useful while programming in C++, is the use of <b>std::stringstream</b> to convert different datatypes to <b>std::string</b>. Fortunately, the process is the same for all types. That&#8217;s why a generic helper-function is preferable and will simplify the process considerably.</p>
<p>In order to use stringstreams, the library <b>&#60;sstream&#62;</b> has to be included. The following will create a reusable stringstream helper-function using templates.</p>
<blockquote><p><code>template &#60;typename T&#62; std::string to_string(const T&#38; value) {<br />
std::stringstream os;<br />
os &#60;&#60; value;<br />
return os.str();<br />
}</code></p></blockquote>
<p>The parameter contains the value that will be converted into a string, so you only have to assign a string to the function.</p>
<blockquote><p>// assign a new string to the return value of to_string and show the contents<br />
<code>std::string str = to_string(5.12);<br />
std::cout &#60;&#60; str;</code></p></blockquote>
</div>]]></content:encoded>
</item>

</channel>
</rss>
