I'm currently going nuts with a problem called Caesar. Essentially, you need to build a program that encrypts text that the user enters (so, for example - if you entered the number 1 and the plaintext 'Hi' the code that would come back would read 'Ij' as the program would have encrypted the plaintext message by moving the numbers forward by 1).
I have been trying to write the program step by step - it's really easy to find 'complete' versions of the code online but I want to work out how to do each stage. The walkthrough says that you should try and build the program in the following stages:
- Write pseudocode
- Count command-line arguments
- Access the key
- Validate the key
- Peek under the hood (which is when you insert the 'formula' to encode the text)
I'm stuck on section 4 - which is when you have to check that the value that the user has entered (in my example above the value was 1) and check it is a digit. As things stand, my program is simply checking whether I have one 'argument' but is not checking whether that argument is a digit, so - if the user typed:
./caesar 20 (This should work and does, it has one argument, and both '2' and '0' are digits)
My program would respond with:
Success
20
If the user typed:
./ caesar 20x (This should fail but doesn't. It has only one argument but one character in the argument 'x' is not a digit)
My program would respond with:
Success
20x
The issue seems to be that my program should be looking at each separate character that the user types in their argument. To do this I think I need to run a loop that iterates through each character in the string (which I think I have done). However, something clearly isn't right and I'm struggling! Any help or advice very much appreciated.
Code:#include <cs50.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <math.h> int main(int argc, string argv[]) { if (argc != 2) { printf ("Usage: ./caesar key\n"); } else if (argc == 2) { int Key = atoi(argv[1]); bool isKeyValid = true; int len = strlen(argv [1]); for (int i = 0; i < len; i++) { if (isdigit(argv[1][i]) == false) { isKeyValid = false; printf ("Usage: ./caesar key\n"); i = len; } if (isKeyValid == true) { printf ("Success\n"); printf ("%s\n", argv[1]); i = len; } } } }