Tuesday, September 3, 2013

Int to String Conversions in C++

Working within the ReconstructMe C++ domain, there is a lot of C-style string usage.  This is frustrating to mix with C++ strings for easier search and concatenation style for filename outputs such as a series of filenames

file1.obj
file2.obj
...
fileN.obj

Since there is a mix of C-style and C++ strings, I wanted to share this since the conversion from int to string isn't as straight-forward as I became used to under Python. It's based on another posting: http://forums.codeguru.com/showthread.php?359716-convert-integer-to-string-in-c.

The gist of the post is that the stringstream class is needed.  Using the "<<" operator, the disparate types can be concatenated neatly into a string stream, into a string, and then when needed to be passed to a char* function (here puts as an example)

       int filenum = 1;
       ss << fname << filenum++;
       std::string tempFname = ss.str();
       puts("Saving File to");
       puts(tempFname.c_str());


Due to the nature of the input, we ended up extending it into a function that parses for the first dot "." character to separate extension from base file name.
 
Since the file name will be coming in via the command line input, the outputFileName function uses argc and argv.  While it's a bit of extra work since it's re-processing the full file name each time it is called, it's used a small number of times and a quick function with reasonable file name sizes.

std::string outputFileName(int argc, char* argv[], int &fnum)
{   
    std::string fname;
    std::string name = fname= "test.obj";
   
    if(argc > 1)
        fname = argv[1];

    std::string extension = "";
    std::string basename = "";
    bool reachedDot = false;
    for(unsigned int i = 0; i < fname.length(); i++)
    {
        if(reachedDot)
            extension += fname[i];

        if(fname[i] == '.')
            reachedDot = true;

        if(!reachedDot) // do it this way to avoid "." inclusion
            basename += fname[i];
    }

    std::stringstream ss;   
    ss<< basename << fnum++ << "." << extension;
    name = ss.str();
    return name;

}


No comments:

Post a Comment