title: C - scanf() vs gets() vs fgets()
body: <p>I've been doing a fairly easy program of converting a string of Characters (assuming numbers are entered) to an Integer.</p>
  
  <p>After I was done, I noticed some very peculiar "bugs" that I can't answer, mostly because of my limited knowledge of how the <code>scanf()</code>, <code>gets()</code> and <code>fgets()</code> functions work. (I did read a lot of literature though.)</p>
  
  <p>So without writing too much text, here's the code of the program:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  #define MAX 100
  
  int CharToInt(const char *);
  
  int main()
  {
      char str[MAX];
  
      printf(" Enter some numbers (no spaces): ");
      gets(str);
  //  fgets(str, sizeof(str), stdin);
  //  scanf("%s", str);
  
      printf(" Entered number is: %d\n", CharToInt(str));
  
      return 0;
  }
  
  int CharToInt(const char *s)
  {
      int i, result, temp;
  
      result = 0;
      i = 0;
  
      while(*(s+i) != '\0')
      {
          temp = *(s+i) &amp; 15;
          result = (temp + result) * 10;
          i++;
      }
  
      return result / 10;
  }
  </code></pre>
  
  <p>So here's the problem I've been having. First, when using <code>gets()</code> function, the program works perfectly.</p>
  
  <p>Second, when using <code>fgets()</code>, the result is slightly wrong because apparently <code>fgets()</code> function reads newline (ASCII value 10) character last which screws up the result.</p>
  
  <p>Third, when using <code>scanf()</code> function, the result is completely wrong because first character apparently has a -52 ASCII value. For this, I have no explanation.</p>
  
  <p>Now I know that <code>gets()</code> is discouraged to use, so I would like to know if I can use <code>fgets()</code> here so it doesn't read (or ignores) newline character.
  Also, what's the deal with the <code>scanf()</code> function in this program?</p>