title: [C++]Why Iterating over a std::string using std::stringstream gives an exception character?
body: <p>I'm trying to implement a simple format function that fills in the corresponding content based on the given format character.<br />
  I use <code>std::stringstream</code> to convert the given format string into a stream, and then take out the characters one by one. Then, based on the individual characters, fill in the relevant content into the output stream.
  The format string is given in <code>std::string</code> type.</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;sstream&gt;
  #include &lt;string&gt;
  
  int main() {
      std::string fmt = &quot;[%t]%Y-%M-%D&lt;%H:%m:%s&gt;:%c&quot;;
      std::stringstream s_res;
      std::stringstream s_fmt(fmt);
      while (s_fmt.good()) {
          char c = (char) s_fmt.get();
          if (c == '\0') break; // I'm not sure this stagement is necessary.
          if (c == '%') {
              switch (s_fmt.peek()) {
                  case 't':
                      s_res &lt;&lt; &quot;Type&quot;;
                      break;
                  case 'Y':
                      s_res &lt;&lt; &quot;Year&quot;;
                      break;
                  case 'M':
                      s_res &lt;&lt; &quot;Month&quot;;
                      break;
                  case 'D':
                      s_res &lt;&lt; &quot;Day&quot;;
                      break;
                  case 'H':
                      s_res &lt;&lt; &quot;Hour&quot;;
                      break;
                  case 'm':
                      s_res &lt;&lt; &quot;min&quot;;
                      break;
                  case 's':
                      s_res &lt;&lt; &quot;sec&quot;;
                      break;
                  case 'c':
                      s_res &lt;&lt; &quot;content&quot;;
                      break;
              }
              s_fmt.get();
              continue;
          }
          s_res &lt;&lt; c;
      }
      std::cout &lt;&lt; s_res.str();
      return 0;
  }
  
  </code></pre>
  <p>As expected, the program should output something like this:</p>
  <pre><code>Expected output: [Type]Year-Month-Day&lt;Hour:min:sec&gt;:content
  </code></pre>
  <p>But at the end of the expected output, there is a strange character:</p>
  <pre><code>Actual Output:[Type]Year-Month-Day&lt;Hour:min:sec&gt;:content
  ========================================================^
  </code></pre>
  <p>I checked for a long time and was very troubled to find no credible explanation or concrete solution.</p>
  <p>Is this a problem caused by encoding?</p>
  <p>How can I solve this issue?</p>