Question

My program needs to accept a non-negative integer in a command-line argument. I also must use

int main(int argc, string argv[])

to declare main.

My Code:

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

int main(int argc, string argv[])
{
    if (argv[1] < 0)
    {
        printf("Give one non-negative integer.\n");
        return 1;
    }
}

My problem: When I input -1 as my command-line argument, my program doesn't printf or stop running. It goes on to the next block of code. What can I do to fix it (bearing in mind that I need to keep that exact declaration of main), and why is this current code wrong?

Was it helpful?

Solution

argv is an array of strings, so you need a function to convert the string to an integer, atoi is the function you are looking for.

if (atoi(argv[1]) < 0)

In real code, you may check for invalid command line arguments.


I guess in <cs50.h>, there is a line:

typedef char *string;

you should know that the normal way of declaring main is:

int main(int argc, char* argv[])

OTHER TIPS

So. Two things.

int main(int argc, string argv[])

Notice the type of argv. It is an array of stings that is of unknown length (0 to n).

Next notice this:

if (argv[1] < 0)

This is a comparison operator between a string and an int. Now, strings can easily have integer values (everything is bits once you go down far enough) so.. if the string's value is less than 0, it'll do as you expect. The problem is that this will probably never fire. Needless to say, C will allow you to do this, because typing for it is kinda... well... it won't care if you do something like compare strings and ints.

You can take a look here: Converting string to integer C which will help you understand how to convert a string to an integer value.

a quick exert from the linked SO question above:

int num = atoi(s);

So you could do instead...

if (atoi(argv[1]) < 0)

or

int argument = atoi(argv[1])
if (argument < 0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top