title: How to count the number of multibyte characters?
body: <p>I'd like to get 5 instead of 10 for the following program. Does anybody know how to fix the code to count the number of multibyte characters? Thanks.</p>
  
  <pre><code>/* vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8: */
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;wchar.h&gt;
  #include &lt;locale.h&gt;
  
  size_t nchars(const char *s) {   
      size_t charlen, chars;
      mbstate_t mbs;
  
      chars = 0;
      memset(&amp;mbs, 0, sizeof(mbs));
      while (
              (charlen = mbrlen(s, MB_CUR_MAX, &amp;mbs)) != 0
              &amp;&amp; charlen != (size_t)-1
              &amp;&amp; charlen != (size_t)-2
              ) {
          s += charlen;
          chars++;
      }   
  
      return (chars);
  }   
  
  int main() {
      setlocale(LC_CTYPE, "en_US.utf8");
      char * text = "öçşğü";
  
      printf("%zu\n", nchars (text));
  
      return 0;
  }
  </code></pre>
  
  <pre><code>$ ./main.exe 
  10
  </code></pre>