Note that there are some explanatory texts on larger screens.

plurals
  1. POstringstream operator>> fails as function, but works as instance?
    text
    copied!<p>I'm writing simple code that will extract a bunch of name, int pairs from a file. I'm modifying existing code that just uses:</p> <pre><code>string chrom; unsigned int size; while ( cin &gt;&gt; chrom &gt;&gt; size ) { // save values } </code></pre> <p>But I want to use another (similar) input file that has the same first two columns, but are followed by other data (that will be ignored). So I write:</p> <pre><code>string chrom; unsigned int size; string line; while ( getline(cin, line) ) { if( stringstream(line) &gt;&gt; chrom &gt;&gt; size ) { // save values } } </code></pre> <p>But this fails to compile, giving the typical obscene std lib template spew:</p> <pre><code> error: no match for "operator&gt;&gt;" in "std::basic_stringstream&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;(((const std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;&amp;)((const std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;*)(&amp; line))), std::operator|(_S_out, _S_in)) &gt;&gt; chrom" istream:131: note: candidates are: std::basic_istream&lt;_CharT, _Traits&gt;&amp; std::basic_istream&lt;_CharT, _Traits&gt;::operator&gt;&gt;(std::basic_istream&lt;_CharT, _Traits&gt;&amp; (*)(std::basic_istream&lt;_CharT, _Traits&gt;&amp;)) [with _CharT = char, _Traits = std::char_traits&lt;char&gt;] [...another dozen lines...] </code></pre> <p>Right. line isn't a std::string, but some variation of std::basic_string, etc. However, explicitly instantiating the stringstream works. </p> <pre><code>string chrom; unsigned int size; string line; while ( getline(genome, line) ) { stringstream ss(line); if ( ss &gt;&gt; chrom &gt;&gt; size ) { // save values } // Discard remainder of line } </code></pre> <p>Why? What is wrong with the first case? The <a href="http://www.cplusplus.com/doc/tutorial/basic_io/" rel="nofollow noreferrer">example basic_io</a> at the always helpful cplusplus.com works, why doesn't my code? </p> <p>Update: Another point of reference: the temporary stringstream works when the first value extracted is an int instead of a string:</p> <pre><code>unsigned int chrom; // works as int... unsigned int size; string line; while ( getline(cin, line) ) { if( stringstream(line) &gt;&gt; chrom &gt;&gt; size ) { // save values } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload