title: Overloading the istream >> operator for a rational number class. Don't know how to deal with integers
body: <p>I am learning C++ and am doing a project dealing with a class that represents rational numbers (such as ½). I have overloaded the istream <code>&gt;&gt;</code> operator so that it correctly reads rational numbers from the stream.</p>
  
  <p>I am having an issue with taking in an integer into the stream for a rational number. For example if someone types 2 I want it to be read from the stream as 2/1. I have been told using the <code>peek()</code> function would work but I cannot figure out how. Here is the code:</p>
  
  <pre><code>std::istream&amp; operator&gt;&gt;(std::istream&amp; is, Rational&amp; r)
  {
    int p, q;
    char c;
    is &gt;&gt; p &gt;&gt; c &gt;&gt; q;
  
    if (!is)
      return is;
  
    // Require that the divider to be a '/'.
    if (c != '/') {
      is.setstate(std::ios::failbit);
      return is;
    }
  
    // Make sure that we didn't read p/0.
    if (q == 0) {
      is.setstate(std::ios::failbit);
      return is;
    }
  
    r = Rational(p, q);
    return is;
  }
  </code></pre>
  
  <p>It works perfectly unless an integer is input; I want it to be read as <code>(int)/1</code>. </p>
  
  <p>Any suggestions?</p>