title: C++ Compare and replace last character of stringstream
body: <p>I would like to check the following:  </p>
  
  <ol>
  <li>If the last character appended to the <code>stringstream</code> is a comma.</li>
  <li>If it is remove it.  </li>
  </ol>
  
  <hr>
  
  <pre><code>std::stringstream str;
  str &lt;&lt; "["
  //loop which adds several strings separated by commas
  
  str.seekp(-1, str.cur); // this is to remove the last comma before closing bracket
  
  str&lt;&lt; "]";
  </code></pre>
  
  <p>The problem is if nothing is added in the loop, the opening bracket is removed from the string. So I need a way to check whether the last character is a comma. I did that like this:</p>
  
  <pre><code>if (str.str().substr(str.str().length() - 1) == ",")
  {
      str.seekp(-1, rteStr.cur);
  }
  </code></pre>
  
  <p>But I don't feel very good about this. Is there a better way to do this?</p>
  
  <p>About the loop:  </p>
  
  <p>Loop is used to tokenize a set of commands received through sockets and format it to send to another program through another socket. Each command ends with an <code>OVER</code> flag.</p>
  
  <pre><code>std::regex tok_pat("[^\\[\\\",\\]]+");
  std::sregex_token_iterator tok_it(command.begin(), command.end(), tok_pat);
  std::sregex_token_iterator tok_end;
  std::string baseStr = tok_end == ++tok_it ? "" : std::string(*tok_it);
  while (baseStr == "OVER")
  {
      //extract command parameters
      str &lt;&lt; "extracted_parameters" &lt;&lt; ","
  }
  </code></pre>