【发布时间】:2020-05-12 23:37:09
【问题描述】:
所以我需要编写一个加密文本的程序,将 x (argv[1] = x) 添加到提示给用户的文本中。即:
./program 1 //running the program with argv[1] = 1
plaintext: abcd //prompting the user to write characters he want to cipher
ciphertext: bcde // returning plaintext ciphered with the argv[1] "key" = 1
这是我的代码
int main (int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./ceasar key\n");
return 1;
}
else if (argc ==2)
{
int k = atoi(argv[1]);
for (int j = 0, len = strlen(argv[1]); j < len; j++)
{
if (!isdigit(argv[1][j]))
{
printf("Usage: ./ceasar key\n");
return 1;
}
}
for (int j = 0, len = strlen(argv[1]); j < len; j++)
{
if (isdigit(argv[1][j]))
{
string s = get_string("plaintext: ");
printf("ciphertext: ");
for (int i = 0, n = strlen(s); i <= n; i++)
{
if ('@' < s[i] && s[i] < '[')
{
printf("%c", (s[i] - 'A' + k) % 26 + 'A');
}
else if('`' < s[i] && s[i] < '{')
{
printf("%c", (s[i] - 'a' + k) % 26 + 'a');
}
else
{
printf("%c", s[i]);
}
printf("\n");
return 0;
}
}
}
}
}```
The first lines checks if argc !=2, and if argv[1][j] has a non numeric character. Once that is done it will get argv[1] and add it to each character given from the user. but it wont work correctly.
**Any sugestions?**
【问题讨论】:
-
以
2b为关键字尝试您的程序,看看您是否可以确定问题所在。或许阅读man atoi以获得更多“提示”。 -
这能回答你的问题吗? Got stuck with Caesar.c
-
OT:关于:
printf("Usage: ./ceasar key\n");错误消息应该输出到stderr,而不是stdout。建议:fprintf( stderr, "Usage: %s key\n". argv[0] ); -
OT: about:
for (int j = 0, len = strlen(argv[1]); j < len; j++)这将导致编译器输出关于将unsigned值与signed值进行比较的警告。注意:函数:strlen()返回一个size_t(unsigned long int),它正在与变量j中的int值进行比较 -
This may help you实现您的预期输出。输入
key = 1和你的message = "abcd"。
标签: c cs50 caesar-cipher