gpt4 book ai didi

c - Vigenere cs50 在缺少第二个参数时不会提示

转载 作者:行者123 更新时间:2023-11-30 17:01:32 27 4
gpt4 key购买 nike

我不明白为什么它不起作用。当有 3 个或更多参数时它会提示,但当只有一个 Vigenere 参数时它不会提示。我看过其他有同样问题的人,他们说这可以解决......不知道我在这里缺少什么。当我运行 ./vigenere 时,出现段错误。它通常使用 2 个参数(如 ./vigenere bard)工作,并在给出额外参数(如 ./vigenere bard dfads)时提示。

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>




int main(int argc,string argv[])
{

string sKeyWord = argv[1];
int iKeyLength = strlen(sKeyWord);
int iKey[iKeyLength];
string sPlainText = "";
int counter = 0;
int iAccept = 0;
do
{
if(argc != 2) // <-----this should work whats wrong?
{
printf("Invalid argument! Please enter program name and keyword.\n");
return 1;
}
else if(argv[1])
{
for(int i = 0; i < iKeyLength; i++)
{
if (!isalpha(argv[1][i]))
{
printf("Invalid entry, please use letters only.\n");
return 1;
}
else
{
iAccept = 1;
}
}
}
}while(iAccept == 0);


for(int i = 0; i < iKeyLength; i++)
{
iKey[i] = toupper(sKeyWord[i]) - 65;
}

sPlainText = GetString();
int iPlainText = strlen(sPlainText);


for(int j = 0; j < iPlainText; j++)
{
if(!isalpha(sPlainText[j]))
{
printf("%c",sPlainText[j]);
counter++;
}
if(islower(sPlainText[j]))
{
printf("%c",((((sPlainText[j] - 97) + iKey[(j - counter)%iKeyLength])%26)+ 97));
}
if(isupper(sPlainText[j]))
{
printf("%c",((((sPlainText[j] - 65) + iKey[(j - counter)%iKeyLength])%26)+ 65));
}

}
printf("\n");

return 0;
}

最佳答案

我会像这样重写程序的顶部参数处理部分。

int main(int argc, char **argv)
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s key\n", argv[0]);
return 1;
}
char *sKeyWord = argv[1];
int iKeyLength = strlen(sKeyWord);
int iKey[iKeyLength];

for (int i = 0; i < iKeyLength; i++)
{
if (!isalpha(sKeyword[i]))
{
fprintf(stderr, "%s: Invalid character '%c' in key; please use letters only.\n",
argv[0], sKeyword[i]);
return 1;
}
iKey[i] = toupper(sKeyWord[i]) - 'A';
}

…your code to read the text to be enciphered and encipher it, etc…

关键点是在尝试对它执行任何操作之前检查是否存在 argv[1]。我消除了 do { … } while (…); 循环,因为参数在第二次迭代时不会改变。这样就可以消除 iAccept 变量。请注意,错误是在标准错误上报告的,而不是在标准输出上报告的。另请注意,消息前面带有程序名称 (argv[0])。 “使用情况”消息通常是报告问题的最佳方式;这是对运行该程序的人的简单提醒。还要注意,字母检查的错误消息报告了错误的字符;这可以帮助人们了解程序认为错误的地方。

这或多或少是评论建议应该做的事情。

我还没有检查过加密代码;这也可能存在未诊断的问题。不过,SO 上有许多相关问题可以为您提供任何此类问题的答案。

关于c - Vigenere cs50 在缺少第二个参数时不会提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36962074/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com