0

I am working on pset2 Caesar. I have everything done except for the fact that my program allows you to pass negative numbers as a key. Here is my code:

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

int main(int argc, string argv[])
{
// Gets the encryption key
string tempKey;
if (argc != 2 || argv[1] < 0)
{
    tempKey = get_string("What is your key?\n");
}
else if (argc == 2 && argv[1] > 0) {
    tempKey = argv[1];
}
...
[EDIT: unrelated code removed.]
}
1

There are a few problems here. First, it's checking whether a string, argv[1], is greater than 0, which will always be true, no matter what the number that results after the atoi() call may be. All ASCII chars are nonnegative numbers.

Next, the code has a mechanism to prompt for a new key if the one given as a parameter is invalid. However, if a bad key is then entered again, like a negative number, there's no validation performed. A while loop would work nicely for that. (Remember this for vigenere.)

But while that's nice thinking, it's also irrelevant. The instructions clearly say to print usage instructions and terminate the program if the invocation is incorrect - not to prompt for a new key.

Perhaps a close review of the pset instructions are in order, followed by some recoding?

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1

You must log in to answer this question.

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