The use of std::stringstream
std::string showMSD3(int foo)
{
std::stringstream ssOut;
std::string sign;
std::stringstream ss1;
if(foo < 0) {
ss1 << (-1 * foo);
sign = '-';
}
else
ss1 << foo;
std::string s = ss1.str();
ssOut << " foo string: '"
<< sign << s << "'" << std::endl;
if(s.size() > 2)
{
ssOut << " Most Significant Digit 3: "
<< s[2] // 1st digit at offsset 0
<< "\n has hex value: 0x"
<< std::setw(2) << std::setfill('0') << std::hex
<< (s[2] - '0')
<< std::endl;
}
else
ssOut << " Err: foo has only "
<< s.size() << " digits" << std::endl;
return (ssOut.str());
}
and somewhere closer to main (perhaps in main):
// test 1
{
std::cout << showMSD3(123456789) << std::endl;
}
// test 2
{
std::cout << showMSD3(12) << std::endl;
}
// test 3 - handle negative integer
{
std::cout << showMSD3(-123) << std::endl;
}
with output
foo string: '123456789'
Most Significant Digit 3: 3
has hex value: 0x03
foo string: '12'
Err: foo has only 2 digits
foo string: '-123'
Most Significant Digit 3: 3
has hex value: 0x03