Nic*_*nas 1 c++ append char visual-studio
我的 const char* FilePathName看起来像这样:C:\ImportantFile.hex
并且int id = 12345;
我需要定义一个新的const char* FilePathName_ID将带有下划线的 id 附加到原来的,FilePathName看起来像这样: C:\ImportantFile_12345.hex
我已经看过这个,但它不同,因为我使用 const char* 这给了我错误cannot convert from 'const char * ' to 'char'并且需要一个下划线。
我需要最终进行const char*
编辑,我需要保留文件扩展名。
您需要创建一个新std::string对象或一个以 null 结尾的字节字符串。一种简单的方法是这样的:
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();
}
Run Code Online (Sandbox Code Playgroud)
您可以将字符串文字无缝传递给上述函数。
更新:我注意到您可能还需要删除扩展名:
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
}
Run Code Online (Sandbox Code Playgroud)
请参阅 的更新定义append_number。
更新 2:尝试以下程序:
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出应该是:
file_45.hex
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5235 次 |
| 最近记录: |