0

I'm very new to all this and so am struggling a bit with the for loop. Here is my code:

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

int main(int argc, string argv[])
{
    // Promts user if inputs more than one command-line argument
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
    
    // Prompts user if key is composed of characters other than digits
    for (int i = 0, n = strlen(argv[1]); i < n; i++)
    {
        if (!isdigit(argv[1][i]))
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }
        else
        {
            printf("Success!\n");
            return 0;
        }
    }    
}

I'm not sure I understand how I can make my loop work for "./caesar 20x", so that it prompts the user for another key. I've been trying to get my head around it and can't figure itout, would appreciate any leads.

1 Answer 1

0

It's only supposed to terminate the program with the usage message, not prompt for a new key.

The real problem here is that it will only check the first character. Think about it. If a single char is not a number, the test fails and the program needs to terminate. BUT, it's only a success once all the characters are checked. The code needs to check all the characters (finish the loop) before there is success and the success message printed.

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

1
  • Got it, thank you!
    – aymencd
    Commented Dec 30, 2021 at 3:24

You must log in to answer this question.

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