因此,我需要编写一个程序来加密将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?**
答案 0 :(得分:0)
我测试了您的代码。它只打印一个字符,这意味着最后的for loop
返回得太快。该循环仅迭代一次,因为它在迭代结束时返回0
。如果将return 0
与printf("\n")
移出for循环,则代码将起作用。
解决方案;
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;
}
}