2014-03-05 57 views
0

我对C很新颖。我希望能够移动字母'x'的次数来创建基本密码。C凯撒密码ASCII字母换行

我遇到了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"); 
} 

输出:

[email protected] (~/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 
+1

模运算符'%'具有比'+'更高的优先级。如果我是你,我会在'printf()'中使用圆括号。 –

+0

我已经更新了,谢谢。 – JT1

+0

我认为reza的意思是(p [i] + k)%26。 – user1895961

回答

2

在英语中的字母是使用C用作ASCII定义。 'Z'(ASCII 90)后面跟着'{'(ASCII 91)。 要回到“A”,你应该做的所有班次以下列方式:

  1. 由65减去你的ASCII字符它会导致输出介于0 至25(含)。
  2. 添加位移(移位距离)。
  3. 以模26为例,以环绕您的结果。
  4. 再次加65。

请记住,这只适用于英语的大写字母。因此您可能需要使用ctype.h库中的toupper()

如果要为小字符添加类似的功能,请执行上述步骤,将97替换为65. 要检查您是否有小字符或大写,请使用isupper()。 您必须为特殊字符添加更多和特定的代码。

+0

isupper()和islower()绝对是我正在寻找的。 – JT1

+0

对于第1步,int new = p - 65但是,输出是一个字符串。我不应该把它保持为int吗? – JT1

+0

你可以用任何你喜欢的方式来做。我会推荐一个'char',因为它需要更少的内存。 –

0

islower((char)i)检查循环计数器是否是小写字符。

你想测试该位置的字符 - islower(p[i])