Ting Ting - 2 months ago 9
C Question

Program that checks for a negative argv not working?

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
as my command-line argument, my program doesn't
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?


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[])