【发布时间】:2020-12-23 18:45:54
【问题描述】:
我目前正在处理 CS50 中的替换问题,并且我的变量在代码中的行为方式存在问题。 基本上我得到了两个变量plain_text 和key_2。我的问题是这两个变量,尽管我正在创建它们的副本以便它们不会改变,但仍然被分配了它们的副本所获得的值。现在我知道它在某种程度上与变量的范围有关,但我只是不知道如何正确地做到这一点,所以变量的副本会改变而不是原件。
#include <stdio.h>
#include <math.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
string substitute_strings (string plain_text,string key);
int main (int argc, string argv[])
{
for (int i = 0; i < argc; i++)
{
if (argc == 1)
{
printf ("Enter key!\n");
return 1;
}
for (int j = 0; j < strlen (argv[1]); j++)
{
if ((argv[1][j] >= 'a' && argv[1][j] <= 'z') || (argv[1][j] >= 'A' && argv[1][j] <= 'Z'))
{
int var = 0;
}
else
{
printf ("Key can contain only alphabet!");
return 1;
}
}
if (strlen(argv[1]) != 26)
{
printf ("Key must contain 26 characters!\n");
return 1;
}
for (int c = 0; c < strlen (argv[1]); c++)
{
for (int b = c + 1; b < strlen (argv[1]);b++)
{
if (argv[1][c] == argv[1][b])
{
printf ("Character cannot repeat twice in key!");
return 1;
}
}
}
}
string key = argv[1];
string plain_text = get_string ("Enter messege here: \n");
printf("ciphertext: %s\n",substitute_strings (string plain_text , string key));
return 0;
}
**string substitute_strings (string plain,string key_2)**
{
string alphabet_upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string alphabet_lower = "abcdefghijklmnopqrstuvwxyz";
string plain_copy = plain;
for (int m = 0; m < strlen (plain_copy); m++)
{
if (plain_copy[m] >= 'A' && plain_copy[m] <= 'Z')
{
int exit_loop = 0;
for (int n = 0; exit_loop < 1;n++)
{
if (alphabet_upper[n] == plain_copy[m])
{
plain_copy[m] = key_2[n];
exit_loop++;
}
}
}
else if (plain_copy[m] >= 'a' && plain_copy[m] <= 'z')
{
int h = 0;
string key_2_copy = key_2;
while (h < strlen (key_2))
{
key_2_copy[h] = tolower(key_2_copy[h]);
h++;
}
int exit_loop_2 = 0;
int p = 0;
while (exit_loop_2 < 1)
{
if (alphabet_lower [p] == plain_copy [m])
{
plain_copy[m] = key_2_copy [p];
exit_loop_2++;
}
p++;}
}
}
return plain_copy;
}
【问题讨论】:
-
当您尝试增加缩进以格式化此问题时,看起来代码的缩进有点混乱。您可以通过在代码块之前的行和之后的行上使用三个“反引号”标记 (`) 来显示没有额外缩进的代码。
-
这是“为什么用 typedef 隐藏指针是个坏主意”的一个很好的例子。
-
好消息:
strdup()很可能会成为下一个发布的 C 标准的一部分(参见 C2x draft (PDF document)) -
贴出的代码无法编译!编译时,始终启用警告,然后修复这些警告。 (对于
gcc,至少使用:-Wall -Wextra -Wconversion -pedantic -std=gnu11)注意:其他编译器使用不同的选项来产生相同的结果。 -
关于以下陈述;
printf("ciphertext: %s\n",substitute_strings (string plain_text , string key));调用函数时不包括参数类型。唯一需要参数类型的时间是在原型和函数签名中。因此,声明应该是:printf( "ciphertext: %s\n", substitute_strings ( plain_text , key ) );注意水平间距,以便我们人类阅读