Convert int to string using C++

The C++ string class has many advantages and I personally like using it whenever I deal with strings in my C++ programs. Often times I have an integer stored in an int variable which I would like to have represented in string form. This function gives a simple way to convert an int value to a string.

string IntToString(int intValue) {
  char *myBuff;
  string strRetVal;

  // Create a new char array
  myBuff = new char[100];

  // Set it to empty
  memset(myBuff,'\0',100);

  // Convert to string
  itoa(intValue,myBuff,10);

  // Copy the buffer into the string object
  strRetVal = myBuff;
  
  // Delete the buffer
  delete[] myBuff;

  return(strRetVal);
}

There are many other ways to do this same thing, so if you have another way which might work better, please share your method using the comment system below.


Author: DPAK
Created: Dec 1 2005
Categories: C++
TechByte #100

Warning: By visiting this site and/or by using any information contained herein, you agree to the Techbytes.ca terms of use.



Add a comment about this TechByte

If you wish to add a comment regarding this TechByte, please use the form below. Please note that by submitting comments using this form you are allowing all of the information submitted to be visible on this website. Any comments submitted using this form will only be shown on the website if they are approved by the administrators of this site. IF APPROVED, COMMENTS MAY TAKE SEVERAL DAYS TO BE POSTED.

Posted By: (Optional)

Comments:


Other TechBytes: