0

I'm going along with Section 3 and printing "BARFOO" in the caesar program. This is the output from terminal:

Terminal screenshot when entering plain text

This has happened many times with multiple programs and I originally assumed it was a problem with my own code. This time, though, the code was from Section 3. Any reason as to why this is happening?

Here is the code (written by CS50 staff):

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

int main(int argc, string argv[])
{
    // ensure user entered a valid key
    if (argc != 2 || atoi(argv[0]) < 0)
    {
        printf("Usage: ./caesar key\n");
        return 1; 
    }

    // save the key
    int key = atoi(argv[1]);

    // get the plaintext from the user
    string plaintext = GetString();

    // encrypt the plaintext
    for (int i = 0, n = strlen(plaintext); i < n; i++)
    {
        if (plaintext[i] >= 'A' && plaintext[i] <= 'Z')
        {
            plaintext[i] = (plaintext[i] - 'A' + key) % 26;
        }
        else if (plaintext[i] >= 'a' && plaintext[i] < 'z')
        {
            plaintext[i] = (plaintext[i] - 'a' + key) % 26;
        }
    }

    // print out the encrypted message
    printf("%s\n", plaintext);

    return 0;
}
1

When your program outputs something like this, it's likely that you're NOT outputting valid printable char values due to wrong calculations or something.

The printable char values are from 32 to 126 in the ASCII table (inclusive). To check the value of a char you may write something like

printf("%i\n", c);

where c is the char variable that you wanna print its integer value.


UPDATE: why are you checking whether atoi(argv[0]) is < 0? agrv[0] is just the name of the program.

Also, as I told you, calculations result in invalid ASCII values. For example, assuming key is 1 and plaintext[0] is 'a' (i.e., 97). You're doing the following

plaintext[0] = (plaintext[0] - 'a' + key) % 26
               (97           - 97  + 1) % 26
                1                       % 26 = 1 // which is not printable
4
  • As i was following along with the section i have done exactly the same as the instructor and it worked perfectly with him, not for me. Could there be any other reason as to why this is happening? Maybe something specific to my machine?
    – Kareem
    Sep 22 '14 at 6:31
  • @Kareem may you please update your question with the code?
    – kzidane
    Sep 22 '14 at 11:18
  • Question has been updated!
    – Kareem
    Sep 23 '14 at 8:04
  • @Kareem updated the answer!
    – kzidane
    Sep 23 '14 at 12:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .