nktran42
nktran42

Reputation: 11

How to properly iterate through a command-line argument to check if each character is a digit in C?

I am trying to iterate over the second command prompt that a user would enter to verify that each character in the array is indeed a digit.

After looking at ASCII, I know, that the characters 0-9 range from 48-57. I figured out that you could just use isdigit() but am still wondering why my loop does not work as intended.

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

int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

    for(int i=0, n=strlen(argv[1]); i<n; i++)
    {
        if((int)argv[1][i] < 48 && (int)argv[1][i] > 57)
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }
    }
}

Upvotes: 1

Views: 389

Answers (3)

selbie
selbie

Reputation: 104484

Instead of this:

    if((int)argv[1][i] < 48 && (int)argv[1][i] > 57)

This:

    if((int)argv[1][i] < 48 || (int)argv[1][i] > 57)

On a long enough timeline on Stack Overflow, the EBCIDIC crowd will come along to remind us all that it still exists. So instead of hardcoding ordinal values for ascii chars, use the character literal itself. It also makes the code's intent way more obvious:

    if ((argv[1][i] < '0') || (argv[1][i] > '9'))

Putting it altogether with some more cleanup:

for(int i=0, n=strlen(argv[1]); i<n; i++)
{
    char c = argv[1][i];
    if ((c < '0') || (c > '9'))
    {
        printf("Useage: ./caesar key\n");
        return 1;
    }
}

Upvotes: 2

Krishna Kanth Yenumula
Krishna Kanth Yenumula

Reputation: 2567

int main(int argc, string argv[])

String data type is not defined in C. Here you should use char* argv[].
Please see this answer: Does C have a string type?

Remaining issues have been pointed out by other users.

Upvotes: 1

kiran Biradar
kiran Biradar

Reputation: 12732

    if((int)argv[1][i] < 48 && (int)argv[1][i] > 57)
    {
        printf("Useage: ./caesar key\n");
        return 1;
    }

The check should be || not &&.

    if((int)argv[1][i] < 48 || (int)argv[1][i] > 57)
    {
        printf("Useage: ./caesar key\n");
        return 1;
    }

Upvotes: 0

Related Questions