<p>Can I persuade <code>operator&gt;&gt;</code> in C++ to read both a <code>hex</code> value AND and a <code>decimal</code> value?  The following program demonstrates how reading hex goes wrong.  I'd like the same <code>istringstream</code> to be able to read both <code>hex</code> and <code>decimal</code>.</p>
<pre><code>#include &lt;iostream&gt;
#include &lt;sstream&gt;

int main(int argc, char** argv)
{
    int result = 0;
    // std::istringstream is(&quot;5&quot;); // this works
    std::istringstream is(&quot;0x5&quot;); // this fails

    while ( is.good() ) {
        if ( is.peek() != EOF )
            is &gt;&gt; result;
        else
            break;
    }

    if ( is.fail() )
        std::cout &lt;&lt; &quot;failed to read string&quot; &lt;&lt; std::endl;
    else
        std::cout &lt;&lt; &quot;successfully read string&quot; &lt;&lt; std::endl;

    std::cout &lt;&lt; &quot;result: &quot; &lt;&lt; result &lt;&lt; std::endl;
}
</code></pre>

[{'answer_id': 77359, 'author': 'nsanders', 'author_id': 1244, 'author_profile': 'https://Stackoverflow.com/users/1244', 'pm_score': 4, 'selected': False, 'text': '<p>You need to tell C++ what your base is going to be.</p>\n\n<p>Want to parse a hex number?  Change your "is >> result" line to:</p>\n\n<pre><code>is &gt;&gt; std::hex &gt;&gt; result;\n</code></pre>\n\n<p>Putting a std::dec indicates decimal numbers, std::oct indicates octal.</p>\n'}, {'answer_id': 77360, 'author': 'user10392', 'author_id': 10392, 'author_profile': 'https://Stackoverflow.com/users/10392', 'pm_score': 5, 'selected': True, 'text': '<p>Use <a href="http://en.cppreference.com/w/cpp/io/manip/setbase" rel="nofollow noreferrer"><code>std::setbase(0)</code></a> which enables prefix dependent parsing. It will be able to parse <code>10</code> (dec) as 10 decimal, <code>0x10</code> (hex) as 16 decimal and <code>010</code> (octal) as 8 decimal.</p>\n\n<pre><code>#include &lt;iomanip&gt;\nis &gt;&gt; std::setbase(0) &gt;&gt; result;\n</code></pre>\n'}, {'answer_id': 77437, 'author': 'Dave Hillier', 'author_id': 1575281, 'author_profile': 'https://Stackoverflow.com/users/1575281', 'pm_score': -1, 'selected': False, 'text': "<p>0x is C/C++ specific prefix. A hex number is just digits like a decimal one.\nYou'll need to check for presence of those characters then parse appropriately.</p>\n"}]
['https://Stackoverflow.com/questions/77266', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1359466/']