C++ const char* 常量字符串拼接问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AmazingUU/article/details/52987437

项目里要用到循环输出多个文件,每次输出的文件名要不同,否则新生成的就会把原来的替换掉了。那么这就需要文件名里加一个数字来区分,要用到字符串的拼接。结果需要const char*类型,原本打算直接用const char*类型相加得到结果,但是发现不行。转而采取另一种思路,利用熟悉的string类型拼接,最后转为const char*类型。

#include<string>
#include<iostream>
using namespace std;
void main(){
    const char* video_filename=NULL;
    for(int i=1;i<10;i++){
        //const char* 常量字符串拼接
        char ch[2]={0};
        _itoa_s(i,ch,10);//int转char数组
        std::string video_src1="video";
        std::string src2=ch;//char数组自动转为string
        std::string video_src3=".yuv";
        std::string video_name=video_src1+src2+video_src3;
        video_filename = video_name.c_str();//string转const char*
        cout<<video_filename<<endl;
    }
}

效果图:

这里写图片描述

P.S.
CString转const char*:先将CString转为string类型,然后同上处理

std::string path=(CStringA)sFilePath;

猜你喜欢

转载自blog.csdn.net/AmazingUU/article/details/52987437