【发布时间】:2020-10-30 13:46:24
【问题描述】:
我正在尝试编写代码,该代码将从明文字符串输入中获取每个数字,如果是字母,则输出不同的字母,由替换键(26 个字母键)定义。
换句话说,如果字母表是“abcd”并且提供的键是“hjkl”,则输入“bad”将输出“jhl”。
// Regular alphabet is to be used as comparison base for key indexes //
string alphabet = "abcdefghijklmnopqrstuvwxyz";
// Prompt user for input and assign it to plaintext variable //
string plaintext = get_string("plaintext: ");
非字母应按原样打印。
我的想法是通过字母表中的每个索引循环输入数字以查找相应的字母,如果找到,则从字符串中打印相同的索引字符。 (我认为令人困惑)
然而,这个循环在我运行它时会返回一个段错误,但在调试时不会:
// Loop will iterate through every ith digit in plaintext and operate the cipher //
for (int i = 0; plaintext[i] != '\0'; i++) {
// Storing plaintext digit in n and converting char to string //
char n[2] = "";
n[0] = plaintext[i];
n[1] = '\0';
// If digit is alphabetic, operate cipher case-sensitive; if not, print as-is //
if (isalpha(n) != 0) {
for (int k = 0; alphabet[k] != '\0'; k++) {
char j[2] = "";
j[0] = alphabet[k];
j[1] = '\0';
if (n[0] == j[0] || n[0] == toupper(j[0])) {
if (islower(n) != 0) {
printf("%c", key[k]);
break;
} else {
printf("%c", key[k] + 32);
break;
}
}
}
} else {
printf("%c", (char) n);
}
}
怎么了?我在网上寻求帮助,但大多数资源对初学者不太友好。
【问题讨论】:
-
有一个内置函数
strchr()会在字符串中搜索匹配的字符,您不需要编写自己的循环。 -
为什么要为 1 个字符的字符串创建数组?只需使用
char变量即可。 -
isalpha(n)错误,应该引起编译器警告。isalpha()的参数应该是n[0],而不是n。 -
提示:节省时间,启用所有警告。
-
@Barmar strchr(),据我所知,将返回一个指针,我仍然不知道如何使用指针(或者它们究竟是什么)。
标签: arrays c for-loop segmentation-fault cs50