简体   繁体   English

如何在C ++上附加字符串

[英]how to append string on C++

when it calls function, the latest string left only ex) first call "abc" second call "def" best result is "abc"\\n"def" , actual result : "def" 调用函数时,仅保留最新的字符串,例如ex)首先调用“ abc”,第二次调用“ def”最佳结果是“ abc” \\ n“ def”,实际结果是“ def”

visual 6.0 C++ 视觉6.0 C ++

void PrintCSV(CArchive &archiveContent, CStringList &strList, CString szSeparator)
{
    if( strList.IsEmpty() )
        return;

    CString strOneRecord;
    POSITION posTail = strList.GetTailPosition();
    POSITION pos;

    for( pos = strList.GetHeadPosition(); pos != posTail; )
    {
        CString str = strList.GetNext( pos );
        strOneRecord += str;
        strOneRecord += szSeparator;
        strOneRecord += "\t";
    }

    strOneRecord += strList.GetNext(posTail);
    strOneRecord += _T("\r\n"); // windows change a line
    archiveContent.WriteString(strOneRecord);
}

ex) first call "abc" and second call "def" 例如)第一次调用"abc" ,第二次调用"def"

Expected result is "abc\\r\\ndef" 预期结果为"abc\\r\\ndef"

Actual result : "def" 实际结果: "def"

You are correctly appending one string to another string. 您正确地将一个字符串附加到另一个字符串。

The problem is that you overwrite the old file. 问题是您覆盖了旧文件。 You must open the file with CFile::modeNoTruncate and go to the end of the file: 您必须使用CFile::modeNoTruncate打开文件并转到文件末尾:

CFile file;
if (file.Open(filename, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate))
{
    file.SeekToEnd();

    CArchive ar(&file, CArchive::store);
    PrintCSV(ar, strList, szSeparator);
}

You can also obtain a handle to CArchive 's CFile and go to end of file: 您还可以获取CArchiveCFile的句柄并转到文件末尾:

ar.GetFile()->SeekToEnd();

Note that CArchive is commonly used for serialization. 请注意, CArchive通常用于序列化。 If you are not doing serialization then skip CArchive . 如果您不进行序列化,则跳过CArchive Use CFile directly, or use CStdioFile as follows: 直接使用CFile ,或如下使用CStdioFile

CStdioFile file;
if(file.Open(filename, 
    CFile::typeBinary | CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate))
{
    file.SeekToEnd();
    file.WriteString(str);
    file.Close();
}

(add CFile::typeBinary for CStdioFile if you are handling "\\r\\n" yourself) (如果您自己处理"\\r\\n"则为CStdioFile添加CFile::typeBinary

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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