Home > Software engineering >  In C, how can I determine the length of argv[1], when calling a function?
In C, how can I determine the length of argv[1], when calling a function?

Time:01-31

I'm trying to write a program that: 1- must have 2 arguments in the command line. 2- must call a function that checks if the 2nd argument is a digit.

This was my best try:

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

bool only_digits(string s[1]);

int main(int argc, string argv[])
{
    // Check how many arguments were typed in the command line.
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
    // Check that argv[1] is a digit.
    bool is_digit = only_digits(&argv[1]);
    if (is_digit)
    {
        printf("Usage: ./caesar key\n./caesar ");
        return 1;
    }
    return 0;
}

bool only_digits(string s[1])
{
    for (int i = 0, n = strlen(s[1]); i < n; i  )
    {
        int is_digit = isdigit(s[1][i]);
        if (is_digit == 0)
        {
            return 1;
        }
    }
    return 0;
}

When I run this program and submit a string as the 2nd argument in the command line, the result is "Segmentation fault (core dumped)". I get that the problem is that "s[1]" in my function doesn't include a NULL character at the end, so the function can't find the end of the string. However, when I include the function in main, the problem disappears.

int main(int argc, string argv[])
{
    // Check how many arguments were typed in the command line.
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
    // Check that argv[1] is a digit.
    for (int i = 0, n = strlen(argv[1]); i < n; i  )
    {
        int is_digit = isdigit(argv[1][i]);
        if (is_digit == 0)
        {
        printf("Usage: ./caesar key\n./caesar ");
        return 1;
        }
    }
    return 0;
}

But as I need to do this calling a function, I need help :P

CodePudding user response:

The function must be declared like

bool only_digits(string s);

and called like

bool is_digit = only_digits(argv[1]);

The function definition can look the following way

bool only_digits( string s )
{
    if ( *s == '\0' ) return false;

    while ( isdigit( ( unsigned char )*s ) )   s;

    return *s == '\0';
}

Though it would be better to declare the function without changing its definition like

bool only_digits( const char *s );

CodePudding user response:

I actually solved my problem a few minutes after I've posted... I simply added:

    bool only_digits(string s);    
...
    string argument = argv[1]; // <- this line!
    bool is_digit = only_digits(argument);

And of course, I removed "[1]" from the function definition... :)

  •  Tags:  
  • Related