我不能在C中使用printf打印字符

t9aqgxwy  于 2023-02-07  发布在  其他
关注(0)|答案(1)|浏览(141)

我试图打印输出的函数“字符旋转(字符c,整数n)”,但它只会打印数字,而不是字符。任何帮助是感谢它。

#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

bool only_digits(string arg);
char rotate(char c, int n);

int main(int argc, string argv[])
{

   // Make sure program was run with just one command-line argument

   if (argc !=2)

    {
    printf("Usage: ./caesar key\n");
    return 1;
    };

    // Make sure every character in argv[1] is a digit
    if ( only_digits(argv[1])==0)
    {
     printf("Usage: ./caesar key\n");
     return 1;
    };

     // Convert argv[1] from a `string` to an `int`
     int key = atoi(argv[1]);

    // Prompt user for plaintext//
    string text = get_string("plaintext: \n");

    // For each character in the plaintext:

     printf("ciphertext: ");

     for (int i = 0; i < strlen(text); i++)
     {
      char ch = (rotate(text[i], key));
      
      printf("%c", ch);
     };

}

bool only_digits(string arg)
{
      // Rotate the character if it's a letter
     for (int i = 0; i < strlen(arg); i++)
     {
         if (!isdigit(arg[i]))
         {
          return false;
         }
     }
     return true;
}

char rotate(char c, int n){

     if (isupper(c))
     {
          c -=65;
          c = (c + n) % 26;
          c = c + '0';
          return c;
     }

      else if (islower(c))
     {
          c -=97;
          c = (c + n) % 26;
          c = c + '0';
          return c;

     }
      else
      return c;

}

我尝试了不同的方法将整数转换为字符,并尝试使用调试器和printf语句来找出导致这种情况的原因。
编辑1:在我最初的帖子中,我删除了一堆代码,认为这与我的问题无关,但对这些部分提出了一些问题,所以希望现在它更清楚了。当我键入abc时,它根本不打印任何东西,只是“纯文本:“

toe95027

toe950271#

OP最终确定了一个主要问题。
'A''a'应被减去时,代码是'0'的子字符串。
要处理其他问题:

ch < 0出现问题时is...(ch)出现问题

最好使用unsigned char

避免像65这样的幻数
避免负值和溢出错误

c + n可能溢出
总和可能是负数,所以让我们用某些正数来计算。

不必要的else

// In main(), bring `key` into the range [0...25];
int key = atoi(argv[1]);
key &= 26;  // key now in the [-25 ... 25] range
if (key < 0) key += 26; 

// n is in the 0...25 range.
static char rotate(char c, int n) {
  unsigned char uch = (unsigned char) c;
  if (isupper(uch))  {
    uch = (uch - 'A' + n) % 26;
    return uch + 'a';
  }
  if (islower(uch))  {
    uch = (uch - 'a' + n) % 26;
    return uch + 'a';
  }
  return c;
}

相关问题