您将单个字符的地址传递到decryption
buf=input.get();
// ...
encryption(&buf, &buf1, key);
然后你将它视为指向一个空终止 string.
while(*ptemp){
// ...
ptemp++;
}
这不会很好地发挥作用,因为ptemp
首先并不指向以空结尾的字符串。当你这样做的那一刻ptemp++
你正处于未定义行为领域。
除此之外,还有许多其他陷阱(不要循环.eof()
,例如)和潜在的改进。
Edit哦,还有作业
w = e;
and
e = w;
没有任何效果(您将指针值分配给本地函数参数;返回后,这些变量甚至不再存在)。
这是一个经过清理的镜头,我会expect做你想做的事:住在科利鲁 http://coliru.stacked-crooked.com/a/d3952fc9f07d3410
#include <iostream>
#include <fstream>
using namespace std;
int chooseKey() {
cout << "Give a number from 1-26: ";
int key_number;
while((!(cin >> key_number)) || (key_number < 1 || key_number > 26)) {
cout << "Your number have to be from 1-26 (" << key_number << "). Retry: ";
cin.clear();
}
return key_number-1;
}
template <typename InIt, typename OutIt>
void encryption(InIt f, InIt l, OutIt out, int key) {
for (InIt ptemp = f; ptemp != l; ++ptemp)
{
if(isalpha(*ptemp))
{
char base = islower(*ptemp)? 'a' : 'A';
*out++ = base + (*ptemp - base + key) % 26;
} else
*out++ = *ptemp;
}
}
void Caesar(const char *inputFile, const char *outputFile, int key, int mode) {
ifstream input(inputFile);
ofstream output(outputFile);
istreambuf_iterator<char> init(input), end;
ostreambuf_iterator<char> outit(output);
encryption(init, end, outit, mode? key : 26-key);
}
int main() {
int key, mode;
key = chooseKey();
cout << "1 or 0: ";
cin >> mode;
Caesar("test.cpp", "coded.txt", key, mode);
}