0

Hope you are doing well, a version of my question has already been asked and I went through some of those responses but it hasn’t helped so far. I am new to coding and working on the Caesar problem sets from CS50!

I am struggling to figure out how to get my code to loop through all the character in the key to confirm that, it is a numeric value before printing the success message. Currently when the user input is 20x, the success message gets printed out and then the error message.

What I believe is happening is that the loop just checks each character in the string, one by one and then prints the message rather than going thought the entire key first. I am not sure if a solution involves integrating the null character in the for loop?

I have been stuck at this for two weeks and would be very grateful for any help or tips!

Thank You :-)

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

/// Declare Variable 
int k;

int main(int argc, string argv[])
{
    if (argc == 2)
   {
      for(int i = 0, n = strlen(argv[1]); i < n ; i++)
      {
        if(isdigit(argv[1][i]) == 0)
         {
            printf("Usage: ./caesar key\n");
            return 1;
         }    
       else 
        {
            printf("Success\n %s\n", argv[1]);
            k = atoi(argv[1]);
        }
     }

  }
     else 
     {
       printf("Usage: ./caesar key\n");
     }
}






















1 Answer 1

1

Spare your "Success" for when you've tested them all (after the loop). If execution reaches code after the loop, this means you haven't found a reason to complain/quit within, and that there's no non-digit character in the first command line argument.

BTW, one would usually write if (!isdigit(argv[1][i])), ! being the logical negation "not" (zero becomes 1/true, non-zero becomes zero).

2
  • Thank You for taking the time to help! appreciated it!!
    – mo_coder
    Commented Dec 10, 2019 at 16:00
  • Super useful answer, was stuck with this for a while!
    – FGK
    Commented Mar 21, 2020 at 10:59

You must log in to answer this question.

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