Home > database >  I can't print character in C using printf
I can't print character in C using printf

Time:02-05

I am trying to print the output of the function "char rotate(char c, int n)" but it will print only the numbers and not the characters. any help is appreciate it.

#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;


}

I tried different ways of casting the integers into characters and experimenting with a debugger and using printf statement to figure out what's causing this to no avail.

Edit1: in my original post I deleted bunch of my code thinking it's not relevant to my issue but some of the questions asked about those parts, so hopefully now it's more clear. when I type abc it print no thing at all, just "plaintext: "

CodePudding user response:

OP eventually determined a major issue.

Code was substring a '0' when an 'A' or 'a' should have been subtracted.


To handle other issues:

is...(ch) has trouble when ch < 0

Best to use unsigned char.

Avoid magic numbers like 65

Avoid negatives and overflow errors

c n may overflow

The sum may be negative. So let us work with certain positive numbers.

Unneeded 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;
}
  • Related