我是C的新手。我希望能够将字母“x”字母移动一次以创建基本密码。
我遇到了islower()函数的问题。我正在使用“我”,但是,我无法将其更改为角色。
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
string p;
int main(int argc, string argv[])
{
//if argument count does not equal 2, exit and return 1
if (argc != 2)
{
printf("Less or more than 2 arguments given, exiting...\n");
return 1;
}
else //prompt user for plaintext to encrypt
{
p = GetString();
}
//take the second part of the array (the int entered by user) and store as k (used as the encryption key)
//string k = argv[1];
int k = atoi(argv[1]);
//function:
// c = (p + k) % 26;
//iterate over the characters in the string
//p represents the position in the alphabet of a plaintext letter
//c likewise represents a position in the alphabet
char new;
for (int i = 0, n = strlen(p); i < n; i++)
if (islower((char)i))
{
//printf("%c\n", p[i] + (k % 26));
printf("This prints p:%s\n", p);
printf("This prints i:%d\n", (char)i);
printf("This prints k:%d\n", k);
printf("This prints output of lower(i):%d\n", islower(i));
new = (p[i] - 97);
new += k;
//printf("%d\n", new %26 + 97);
//printf("i = |%c| is lowercase\n", i);
printf("%c\n", new % 26 + 97);
}
else {
//printf("%c", p[i] + (k % 26));
printf("This prints p:%s\n", p);
printf("This prints i:%d\n", (char)i);
printf("This prints k:%d\n", k);
printf("This prints output of lower(i):%d\n", islower(i));
new = (p[i] - 65);
new += k;
//printf("%d\n", new % 26 + 65);
//printf("i = |%c| is uppercase\n", i);
printf("%c\n", new % 26 + 65);
}
printf("\n");
}
输出:
jharvard@appliance (~/Dropbox/CS50x/pset2): ./caesar2 1
zZ < here is my input
This prints p:zZ
This prints i:0
This prints k:1
This prints output of lower(i):0
G < here is fails, lower case z should move to lower case a
This prints p:zZ
This prints i:1
This prints k:1
This prints output of lower(i):0
A < here is a success! upper case Z moves to upper case A
答案 0 :(得分:2)
英文字母用于C中定义的ASCII格式。 'Z'(ASCII 90)后跟'{'(ASCII 91)。 要回到“A”,您应该按以下方式完成所有轮班:
请记住,这仅适用于英语的大写字母。因此,您可能希望使用toupper()
库中的ctype.h
。
如果要为小字符添加类似功能,请执行上述步骤,将65替换为97。
要检查您是否有小角色或大写字母,请使用isupper()
。
您必须为特殊字符添加更多特定代码。
答案 1 :(得分:0)
islower((char)i)
检查循环计数器是否为小写字符。
您想测试该位置的角色 - islower(p[i])
。