**已关闭。**此问题需要debugging details。它目前不接受回答。
编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答这个问题。
9天前关闭。
Improve this question的
我正在尝试解决the substitution problem on CS50 course。在我完成它之后,我试图编译,但它不能正常工作。它总是返回./sustitiuion键部分,即使我给予true键。你能看出哪里不对吗?
当我检查钥匙的部分似乎不正确,我几乎肯定不应该有问题,因为我在互联网上检查了相同的部分,它几乎是相同的。
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./substituion key \n");
return 1;
}
//validate the key!
string key = argv[1];
for (int i = 0; i < strlen(key); i++)
{
if (!isalpha(key[i]))
{
printf("Usage: ./substitution key\n");
}
}
for (int j = 0; j < strlen(key); j++)
{
for (int k = 0; k < strlen(key); k++)
{
if (toupper(key[j]) == toupper(key[k]))
{
printf("Usage: ./substitution key \n");
return 1;
}
}
}
if (strlen(argv[1]) != 26)
{
printf("Usage: ./substituion key \n");
return 1;
}
字符串
为什么这门课的问题这么难?
1条答案
按热度按时间kt06eoxx1#
问题出在测试重复字母的代码中:如果索引
j
和k
不同,则只应检查字母是否不同。@chux建议的一种有效方法是从j + 1
迭代k
到字符串的长度。下面是一个修改过的循环:
字符串
更一般地说,您应该计算一次字符串长度并将其存储到变量中,以避免在每次循环迭代时重复计算。编译器也许能够优化这些对
strlen
函数的调用,但在C中使用j < strlen(key)
作为循环测试是不好的。以下是修改后的版本:
型