title: Two-way C++ communication over serial connection
body: <p>I am trying to write a really simple C++ application to communicate with an Arduino. I would like to send the Arduino a character that it sends back immediately. The Arduino code that I took from a tutorial looks like this:</p>
  
  <pre><code>void setup()
  {
      Serial.begin(9600);
  }
  
  void loop()
  {
      //Have the Arduino wait to receive input
      while (Serial.available()==0);
  
      //Read the input
      char val = Serial.read();
  
      //Echo
      Serial.println(val);
  }
  </code></pre>
  
  <p>I can communicate with the Arduino easily using GNU screen, so I know that everything is working fine with the basic communication:</p>
  
  <blockquote>
    <p>$ screen /dev/tty.usbmodem641 9600</p>
  </blockquote>
  
  <p>The (broken) C++ code that I have looks like this:</p>
  
  <pre><code>#include &lt;fstream&gt;
  #include &lt;iostream&gt;
  int main()
  {
      std::cout &lt;&lt; "Opening fstream" &lt;&lt; std::endl;
      std::fstream file("/dev/tty.usbmodem641");
      std::cout &lt;&lt; "Sending integer" &lt;&lt; std::endl;
      file &lt;&lt; 5 &lt;&lt; std::endl; // endl does flush, which may be important
      std::cout &lt;&lt; "Data Sent" &lt;&lt; std::endl;
      std::cout &lt;&lt; "Awaiting response" &lt;&lt; std::endl;
      std::string response;
      file &gt;&gt; response;
      std::cout &lt;&lt; "Response: " &lt;&lt; response &lt;&lt; std::endl;
  
      return 0;
  }
  </code></pre>
  
  <p>It compiles fine, but when running it, some lights flash on the Arduino and the terminal just hangs at:</p>
  
  <blockquote>
    <p>Opening fstream</p>
  </blockquote>
  
  <p>Where am I going wrong?</p>