user14274675
user14274675

Reputation: 11

Why is my loop not checking the argv for alphabets and printing out for an Error?

enter image description hereMy program takes in Command Line arguments from user and checks to see:

For Argv2 which is stored as a string, if there are any alphabets or "symbols" , the program will output "Usage: ./caesar key".

For example if Command Line argument is:

"./caesar 20", then the program will print out success

However, if its " ./caesar 20x" the program will output "Usage: ./caesar key".

But my program prints "Success" when I input "./caesar 20x"enter image description here

My code whole code is as follows:

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

int main(int argc, string argv[])
{
    if (argc > 1 && argc< 3)
    {
       printf("Success\n");
    }
    else
    {
       printf("Usage: ./caesar key\n");
    }

    for( int i=0; i < argc ; i++ )// Loop to check each element of the Array
    {
         if ( isalpha(argv [1][i] ) )// Function to check if each character is a digit or not
         {
                printf("Success\n");
         }
         else
         {
                printf("Usage: ./caesar key\n");
         }
    }
}

Upvotes: 0

Views: 91

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

For starters this condition

if (argc > 1 && argc< 3)

simpler to rewrite like

if ( argc ==  2 )

This loop

for( int i=0; i < argc ; i++ )

does not make sense. You need to travers the string pointed to by the pointer argv[1].

Within the loop you are using the function isalpha As a result for each character of the string "20x" the function will return logical true.

Substitute the loop for the following loop

char *p = argv[1];

while ( *p && isdigit( ( unsigned char )*p ) ) ++p;

if ( *p == '\0' )
{
    printf("Success\n");
}
else
{
    printf("Usage: ./caesar key\n");
}

Though it would be better to use the standard function strtol instead of such a loop.

Upvotes: 3

Related Questions