简体   繁体   中英

Append integer to end of const char* c++

I have const char* FilePathName which looks like this: C:\\ImportantFile.hex
And an int id = 12345;
I need to define a new const char* FilePathName_ID that would append the id with an underscore to the original FilePathName to look like this: C:\\ImportantFile_12345.hex
I have looked at this but its different as I am using const char* which gives me the error cannot convert from 'const char * ' to 'char' and need an underscore.
I need to end up with a const char*
EDIT I need to keep the file extension.

You need to create a new std::string object or a null-terminated byte string. One easy way is this:

std::string append_number(std::string const& x, unsigned int num, char sep = '_') {
    std::stringstream s;
    s << strip_extension(x) << sep << num;
    return s.str();
}

You can pass a string literal to the above function seamlessly.

Update: I notice that you probably also need to strip the extension:

std::string strip_extension(std::string x, char ext_sep = '.') {
     return x.substr(0, x.find_last_of(ext_sep));
}

std::string get_extension(std::string const& x, char ext_sep = '.') {
     return x.substr(x.find_last_of(ext_sep) + 1); // no error checking 
}

See updated definition of append_number .

Update 2: Try the following program:

#include <string>
#include <iostream>
#include <sstream>

std::string strip_extension(std::string const& x, char ext_sep = '.') {
     return x.substr(0, x.find_last_of(ext_sep));
}

std::string append_number(std::string const& x, unsigned int num, char sep = '_') {
        std::stringstream s;
        s << strip_extension(x) << sep << num << '.' << get_extension(x);
        return s.str();
    }

int main() {
  std::cout << append_number("file.hex", 45) << std::endl;
}

The output should be:

file_45.hex
 ostringstream oss;
 oss << FilePathName << "_" < id;
 const char* FilePathNameID = oss.str().c_str();

As mikerobi said, you can use sprintf to deal with it:

char szAppended[MAX_PATH+10]; // ensure to have enough space for the path and ID
char szNoExt[MAX_PATH];
strcpy(szNoExt, FilePathName);
char *pExt = strrchr(szNoExt, '.');
*pExt = '\0';
sprintf(szAppended, "%s_%d.%s", szNoExt, id, pExt + 1);

You should probably also add some memory checks for the existence of extension.

Note: Any const char * returned via 'c_str()' from a std::string will only be valid as long as the std::string is in scope. You can obtain the pointer but after the string is gone it will be garbage.

You should be able to pass a char * into a function taking a const char * - it sounds like the primary issue may be creating/keeping a valid pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM