#include <iostream>
char convert( int n )
{
if ( n < 0 || n > 9 ) return'-';
return'0' + n;
}
int main()
{
for ( int n = -2; n < 12; n++ ) std::cout << convert( n ) << '\n';
}
The following also works (your code with the extra "const"), but I don't think it is very pretty.
1 2 3 4 5 6 7 8 9
constchar * convert (int n)
{
switch( n )
{ case 0: return"0"; case 1: return"1"; case 2: return"2";
case 3: return"3"; case 4: return"4"; case 5: return"5";
case 6: return"6"; case 7: return"7"; case 8: return"8";
case 9: return"9"; default: return"-";
}
}
Staggeringly, this one also works:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
constchar * convert( int n )
{
if ( n < 0 || n > 9 ) return"-";
constchar * C[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
return C[n];
}
int main()
{
for ( int n = -2; n < 12; n++ ) std::cout << convert( n ) << '\n';
}
#include <iostream>
usingnamespace std;
constchar * convert( int n )
{
if ( n < 0 || n > 9 ) return"-";
constchar *C = "0\0""1\0""2\0""3\0""4\0""5\0""6\0""7\0""8\0""9" ;
return &C[n*2];
}
int main()
{
for ( int n = -2; n < 12; n++ ) std::cout << convert( n ) << '\n';
}