c无法将字符串复制到文件中

时间:2013-08-27 15:12:42

标签: c++ string

我正在尝试将部分加密的字符串保存到文件中。我现在已经被困了几个小时,我不明白错误在哪里。 这是功能:

void cryptData(string & rawTxt, string & path) {

    // the rawTxt is OK. Path is too.

    int c(0), counta(0);
    while( rawTxt[c] != '\0') { // Reading every char from the string.

        if(c <= 122) {
            // First 123 char won't be crypted. 
            // Here I do nothing to rawTxt
        }
        else { // All remaining chars will be crypted

            rawTxt[c] = cryptByte(counta, rawTxt[c]); // Replace current char at position c
                                                      // by a crypted char.
            counta++;

            if(counta > 36) // counta used for crypting,
                counta = 0;
        }
        c++;
    } 

    ofstream toDat(path.c_str() ); // Save recrypted .dat file
    toDat << rawTxt.c_str();  // HERE the first 123 chars are not copied in my file... 
}


// Crypt chars
char cryptByte(int counta, char b) {
    string plainEncryptionKey("odBearBecauseHeIsVeryGoodSiuHungIsAGo");
    b+= (char) plainEncryptionKey[counta];
    return b;
}

我无法理解为什么123个第一个字符未保存在我的文件中。 rawTxt字符串从程序的开头到结尾具有相同的长度。请我疯了!

编辑: 我很抱歉,我的字符串rawTxt是解密文件的结果,该文件在BEGINNING中有123个随机字符。因此,这些随机字符在解密算法中被消除。我愚蠢地编写了加密算法,但没有把这123个字符放回原来的位置。 当我意识到我的代码适用于另一个字符串时,我得到了提示。 我的错。谢谢你的帮助!

3 个答案:

答案 0 :(得分:1)

嗯......我只是在这条线上徘徊:

b+= (char) plainEncryptionKey[counta];

可能是char b从可读字符(即文本)转变为不可读的字符,还是像换行符或carriadge返回一样覆盖行的开头?

如果你做'a'+'a'你就得不到'a'你得到的......实际上我不确定你得到了什么,但是它的纯文本是“频谱”。

也许您只想检查您的cryptByte是否产生可读字符....或以二进制方式查看您的文件?

答案 1 :(得分:0)

我尝试编译它但是我用-Wall和gcc编译器得到了这个错误:

  

'std :: ofstream toDat'具有初始化程序但不完整的类型`

通过加入 fstream 库,我设法让它发挥作用。它希望它有所帮助。因为它实际上是打印角色,如果你在 std :: cout 中输出它。

答案 2 :(得分:0)

您可以使用C++11简化很多:

void cryptData(string & rawTxt, string & path) {
    string plainEncryptionKey("odBearBecauseHeIsVeryGoodSiuHungIsAGo");
    int count = 0;
    for (char & c : rawTxt)
        if (c > 122) {
            c = plainEncryptionKey[count];
            count = (count + 1) % 37;
        }
    ofstream toDat(path.c_str());
    toDat << rawTxt;
}