Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Ints and std::string

Status
Not open for further replies.

SmileeTiger

Programmer
Mar 13, 2000
200
US
Can anyone think of a more readable way to convert an int to a std::string then what I have below:

std::string FilePath;
std::stringstream ss;
std::string FileNum;

for(int i=0 ; i < 5; i++)
{
ss << i;
ss >> FileNum;

FilePath = "/blah/blah/FileName" + FileNum + ".txt";
cout << "File to open:" << FilePath << endl;
}
 
I modified Microsoft's itoa() function to use std::string instead of char* and made it a template...
That way it can convert any base instead of just oct, hex & dec.
 
Encapsulate your solution in a function template:
Code:
  template< typename To, typename from >
To lexical_cast( From f )
{
    To t;
    stringstream stream;
    stream << f;
    stream >> t;
    return t;
}


FilePath = "/blah/file" + lexical_cast<string>(num) + ".txt";

Add error checking.

It works for converting anything to anything, assuming the <<-input representation of one can convert to the >>-output representation of another.


See for the "real" lexical_cast, which has much better error cheching than this one.
 
Since it is just from 0 to five....

Code:
for(int i=0 ; i < 5; i++)
{
  char num = (char)(i + (int)'0');
  FilePath = "/blah/blah/FileName" + num + ".txt";
  cout << "File to open:" << FilePath << endl;
}

should work, fairly clear what your doing and why, and is less lines... The stream is better code in some respects, worse in others. writing a itoa or a general function as others has mentioned would be the way to go if you had to do it a million times.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top