【问题标题】:Caesar Code program not working for letter 'Z'. What's wrong here?凯撒密码程序不适用于字母“Z”。这里有什么问题?
【发布时间】:2020-09-09 18:45:05
【问题描述】:
#include <stdio.h>

int main(void)
{
    char a[50];
    gets(a);

    for(int i=0;i<a[i];i++)
    {
        if(a[i]=="z")  //should print a for z
            printf("a");
        else if (a[i]=="Z") //should print A for Z
            printf("A");
        else if(a[i]<="Z"||a[i]<="z") //else print other char+1
            printf("%c", a[i]+1);

    }
}

当 a[i]==Z 时,此代码不会返回 A。它返回 { for z 和 [ for Z. 这里可能有什么问题?为什么 if-else 语句不起作用?

【问题讨论】:

  • 双引号用于字符串。对于字符,请使用单引号。
  • 从编译器读取警告
  • i&lt;a[i] 是一个非常奇怪的循环条件。您确定要这样做,而不是循环到字符串的末尾吗?
  • @brownputin 那么你预计循环什么时候结束?
  • 最后一个else if应该是else if (isalpha(a[i]))

标签: c arrays if-statement encryption char


【解决方案1】:

双引号创建字符串(char 的数组),但 a[i]char。您无法将 char 与字符串进行比较。您需要使用单引号来创建 char 文字。

        if(a[i]=='z')  //should print a for z
            printf("a");
        else if (a[i]=='Z') //should print A for Z
            printf("A");
        else if(isalpha(a[i])) //other letters print char+1
            printf("%c", a[i]+1);
        else // everything else stays the same
            printf("%c", a[i]);

【讨论】:

    【解决方案2】:

    for循环中的条件

    for(int i=0;i<a[i];i++)
    

    没有意义。例如,用户可以输入将放置在数组中某个位置的任何符号,该位置(该符号)的值将小于该位置的值。在这种情况下,循环将被中断。

    看来你的意思

    for ( int i = 0; a[i] != 0; i++ )
    

    此外,函数gets 是不安全的,并且不受 C 标准支持。而是使用标准 C 函数 fgets。例如

    fgets(a, sizeof( a ), stdin );
    

    在 if 语句中,您使用字符串文字,例如 "Z",而不是字符,例如 'Z'

    所以至少要重写 if 语句

        if( a[i] == 'z')  //should print a for z
            putchar( 'a');
        else if (a[i] == 'Z') //should print A for Z
            putchar( 'A');
        else if( ( 'A' <= a[i] && a[i] < 'Z' )|| 
                   ( 'a' <= a[i] && a[i] < 'z' ) ) //else print other char+1
            putchar( a[i] + 1 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 2017-02-08
      相关资源
      最近更新 更多