convert an integer to Char*

I am trying to help someone convert this old C code to work in C++.

Here is the original function

char * 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 "-";
}
}

Error says "return type does not match the function type."
I have tried several things but nothing works.
thanks for any help.
1
2
3
4
5
6
7
8
9
10
11
12
#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
const char * 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>

const char * convert( int n )
{
   if ( n < 0 || n > 9 ) return "-";
   const char * 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';
}

Last edited on
this works on multiple digits and a C coder would get what you were doing, but its going to be slower than yours for single digits.

sprintf(char*, "%i", int);
Last edited on
Since each choice of string is a fixed length...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

const char * convert( int n )
{
   if ( n < 0 || n > 9 ) return "-";
   const char *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';
}
Topic archived. No new replies allowed.