将CString写入文件

时间:2013-11-25 07:47:15

标签: visual-c++ file-io cstring

我正在尝试将cstring写入文件,但到目前为止还没有成功。 我尝试过以下方法:

std::ofstream myfile;
myfile.open(Placering, std::ofstream::out);
myfile << output;
myfile.close();

但这似乎只是将“输出”的地址打印到“myfile”。

然后我尝试了

for(int i = 0; i < output.getlength(); i++){
    myfile << output[i]
}
输出中的每个元素都是

,但这似乎只是将字符的ASCII值打印到“myfile”。

如何正确地将CString写入文件? CString文件的内容可以是HTML和rtf代码。

编辑: 通过将CString转换为CStringA

,我找到了一个解决方案
std::ofstream myfile;
CStringA output = T2A(stringtoprint);
myfile.open(filename, std::ofstream::out);
for(int i = 0; i < output.GetLength(); i++){
    myfile << output[i];
}
myfile.close();

2 个答案:

答案 0 :(得分:1)

我找到了一个解决方案,将CString强制转换为CStringA

myPrintMethod(CString stringtoprint, LPCWSTR myfile){
    std::ofstream myfile;
    CStringA output = T2A(stringtoprint);
    myfile.open(filename, std::ofstream::out);
    for(int i = 0; i < output.GetLength(); i++){
        myfile << output[i];
    }
    myfile.close();
}

答案 1 :(得分:0)

我找到了一个不同的解决方案

myPrintMethod(CString stringtoprint, LPCWSTR myfile){
std::ofstream myfile;
myfile.open(filename, std::ofstream::out);
myfile << CT2A(stringtoprint);
myfile.close();

}