2012-01-30 82 views
-2

我正在使用特定的密钥解密文本的程序。我试图使用replace(),但它似乎没有工作。例如,qwert应解密为hello,但输出为hlllo;在这种情况下中的w被解密为e,但随后被重新解密为l替换行中的特定字符,C++

输入:

xnm ceuob lrtzv ita hegfd tsmr xnm ypwq ktj 
should come out as: 
the quick brown fox jumps over the lazy dog 
I'm getting: 
oga yaacd brozn aox gamav ovar oga lazy dog 

我该如何解决这个问题?

int main() 
{ 
    // ... 
    myFile.open("decrypt.txt"); 
    while (myFile.good()) 
    { 
     getline(myFile, line2); 
     // now line2 is, e.g., "xnm ceuob lrtzv ita hegfd tsmr xnm ypwq ktj" 

     // help here 
     for (int i = 0; i < 26; i++) 
     { 
      replace(line2.begin(), line2.end(), key[i], fox[i]); 
     } 
     v.push_back(line2); 
    } 

    myFile.close(); 

    for (int i = 0; i < numline; i++) 
    { 
     cout << "line " << i <<" = " << v[i] << endl; 
    } 

    return 0; 
} 
+0

好吧,我删除了所有不必要的代码,并解释了一点点。 – acrogenesis 2012-01-30 23:21:19

回答

1

您需要解密每个字符一次。代替有两个数组,keyfox(显然)包含要替换的字符,您可以考虑在输入字符及其解密版本之间构建一个map。然后你可以简单地遍历输入字符串,一次解密一个字符。

std::map<char, char> lookup; 
// populate lookup such that lookup['q'] = 'h', lookup['w'] = 'e', etc. 

// walk over line2, decrypting a character at a time. 
for (int i = 0; i < line2.length(); i++) 
{ 
    char c = line2[i]; 
    char d = lookup[c]; 
    line2[i] = d; 
    // or, if you want to keep it on one line: 
    // line2[i] = lookup[line2[i]]; 
} 
+0

感谢这项工作伟大的小编辑我不得不做 – acrogenesis 2012-02-01 00:19:06

2

通过作出26个单独的替换,后面的那些正在踩上前面的结果。你需要找到一种方法来让每个角色只发生一次替换。

+1

为每个角色做一次提示是_two_字符串,一个来源和一个目的地,并从一个转换到另一个。 – 2012-01-30 23:40:08

+0

我想使用replace_copy但是当我cout v它是空的,就好像它不复制到line3 'for(int i = 0; i <26; i ++){ replace_copy(line2.begin() ,line2.end(),line3.begin(),key [i],fox [i]); } v.push_back(line3);' – acrogenesis 2012-01-31 00:33:40

-1

在C++中,您可以使用方括号来访问和修改字符串元素。例如:

String str("dog"); 
str[1] = 'c'; 
//str = "dcg" 

所以,你可以使用这个符号来代替replace()。如果替换不起作用,那么你的密钥可能是错误的。

+0

这是真的,但这不是问题。替换实际上只是包装了多个作业。 – poolie 2012-01-31 22:26:54