【发布时间】:2013-02-06 04:44:58
【问题描述】:
帮助!我正试图弄清楚我们教授给我们的这段代码 -
#include <stdio.h>
#include <string.h>
void encrypt(int offset, char *str) {
int i,l;
l=strlen(str);
printf("\nUnencrypted str = \n%s\n", str);
for(i=0;i<l;i++)
if (str[i]!=32)
str[i] = str[i]+ offset;
printf("\nEncrypted str = \n%s \nlength = %d\n", str, l);
}
void decrypt(int offset, char *str) {
// add your code here
}
void main(void) {
char str[1024];
printf ("Please enter a line of text, max %d characters\n", sizeof(str));
if (fgets(str, sizeof(str), stdin) != NULL)
{
encrypt(5, str); // What is the value of str after calling "encrypt"?
// add your method call here:
}
}
我们假设做以下事情:
将
C代码转换为C++。将代码添加到“解密”方法以解密加密文本。
更改代码以使用
pointer操作而不是array操作来加密和解密消息。在main方法中,调用“decrypt”方法对密文(str)进行解密。
这是我设法做到的,但我现在几乎被卡住了。特别是因为我没有C 语言的背景。任何帮助,将不胜感激。
#include <iostream>
#include <string.h>
void encrypt(int offset, char *str)
{
std::cout << "\nUnencrypted str = \n" << str;
char *pointer = str;
while(*pointer)
{
if (*pointer !=32)
*pointer = *pointer + offset;
++pointer;
}
std::cout <<"\nEncrypted str =\n" << str << "\n\nlength = ";
}
void decrypt(int offset, char *str) {
// add your code here
}
void main(void) {
char str[1024];
std::cout << "Please enter a line of text max " << sizeof(str) << " characters\n";
if (fgets(str, sizeof(str), stdin) != NULL)
{
encrypt(5, str); // What is the value of str after calling "encrypt"?
// add your method call here:
}
}
【问题讨论】:
-
公平地说,它已经是有效的 C++,因为所有的 C 都是有效的 C++
-
@DanF Not all C.
-
@DanF:
void new(void) {} int main(void) { new(); }! -
@CSE 你听说过 std::string 吗?
-
@ouch,我需要朝着正确的方向前进。代码可以编译,但没有显示长度,任何有关如何启动解密方法的建议都会有所帮助。