Link to home
Create AccountLog in
Avatar of dreamvb
dreamvb

asked on

Returning String from a function - Please Help

Hi can someone please tell me what I may have done wrong with the code below:

Anyway what I want to code to do is allow the user to pass a number convert it to a string, return the string and display it on the screen. I left the code I made below:

#include <iostream>
using namespace std;

char *IntToStr(int n_num){
  char s_buff[25];

  itoa(n_num,s_buff,10);
  return s_buff;

}

int main(){
      int a_numer;
      char *a_str_num; // used to hold the converted number
      a_numer = 512;// number to convert

      a_str_num = IntToStr(512); // do the convert
      cout << a_str_num; // return the result but ant working why.
      return 0;
}

You can give the function a number and it does return. but does not return a vaild number it just returns s single char as shown below:

&#9830;   Press any key to continue

anyway ideas thanks. I not been doing C++ for long so do expect this to be a falt on my part
but I still like to giet if fixed.

anyway thanks.
Avatar of krbatge
krbatge

The string buffer is out of scope by the time you return it.

You need to either pass in a string buffer to the conversion function (which is how itoa works anyway) or return a type like an stl string.

e.g.

#include <string>
using namespace std;

string IntToString(int n)
{
    char s_buff[25];

     itoa(n_num,s_buff,10);
     return string(s_buff);
}

int main(){
     int a_number;
     char *a_str_num; // used to hold the converted number
     a_number = 512;// number to convert

     a_str_num = IntToStr(a_number ).c_str(); // do the convert
     cout << a_str_num; // return the result but ant working why.
     return 0;
}
Sorry - typo in the example...

int main(){
     .
     .
     .

     a_str_num = IntToString(a_number ).c_str(); // do the convert

     .
     .
     .
}
ASKER CERTIFIED SOLUTION
Avatar of nonubik
nonubik

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of dreamvb

ASKER

Thanks nonubik that is now working as I wanted it to.

tell ya I seem to run into a lot of little problums I think it because I am so used to using VB and expect it to be the same. well I am finding it ant :) anyway I am sure I get the hang of it soon.

Thanks agian.
Beware that if you only use nonubik's approach, and are getting away with it you are lucky. When IntToStr returns, the stack space used for the automatic variable s_buff is made available for strcpy to use, if it chooses to do so. If your strcpy implementation happens to use that bit of the stack, which it is perfectly entitled to do, your source buffer will be scribbled on.