title: How to make cin >> not convert float to integer?
body: <p>I have the following simple code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  int main()
  {
     int a;
     std::cout &lt;&lt; "enter integer a" &lt;&lt; std::endl;
     std::cin &gt;&gt; a ;
  
     if (std::cin.fail())
     {
        std::cin.clear();
        std::cout &lt;&lt; "input is not integer, re-enter please" &lt;&lt;std::endl;
        std::cin &gt;&gt;a;
        std::cout &lt;&lt; "a inside if is: " &lt;&lt; a &lt;&lt;std::endl;
     }
     std::cout &lt;&lt; "a is " &lt;&lt; a &lt;&lt;std::endl;
     std::cin.get();
     return 0;
  }
  </code></pre>
  
  <p>When I run the above code and input: <code>1.5</code>, it outputs: <code>a is 1</code>. FYI: I compile and run the code with gcc 4.5.3.</p>
  
  <p>This means that if <code>cin</code> expects an integer but sees a float, it will do the conversion implicitly. So does this mean that when <code>cin</code> sees a float number, it is not in <code>fail()</code> state? Why this is the case? Is it because C++ does implicit conversion on <code>&gt;&gt;</code> operator?</p>
  
  <p>I also tried the following code to decide whether a given input number is integer following idea from this post: <a href="https://stackoverflow.com/questions/7646512/testing-if-given-number-is-integer">testing if given number is integer</a>:</p>
  
  <pre><code>#include &lt;iostream&gt;
  bool integer(float k)
  {
      if( k == (int) k) return true;
      return false;
  }
  
  int main()
  {
     int a;
     std::cout &lt;&lt; "enter integer a"&lt;&lt; std::endl;
     std::cin &gt;&gt; a ;
  
     if (!integer(a))
     {
       std::cout &lt;&lt; "input is not integer, re-enter please" ;
       std::cin.clear();
       std::cin &gt;&gt; a;
       std::cout &lt;&lt; "a inside if is: " &lt;&lt; a &lt;&lt;std::endl;
     }
     std::cout &lt;&lt; "a is " &lt;&lt; a &lt;&lt;std::endl;
     std::cin.get();
     return 0;
  }
  </code></pre>
  
  <p>This block of code was also not able to test whether <code>a</code> is integer since it simply skip the <code>if</code> block when I run it with float input.</p>
  
  <p>So why this is the case when getting user input with cin? What if sometimes I want the input to be <code>189</code>, but typed <code>18.9</code> by accident, it will result in <code>18</code> in this case, which is bad. So does this mean using <code>cin</code> to get user input integers is not a good idea? </p>
  
  <p>thank you.</p>