Home > Back-end >  reading a number from the command line
reading a number from the command line

Time:09-07

Please forgive me for asking this simple question, but I only started C recently with the original C book by Kernigham and Ritchie, using Notepad (as VSCode just throws errors when I try to compile anything and I don't know yet how to overcome that), and using gcc from the command line.

Anyway, the question I have is, how do I read a number from a command line argument?

For example, myProgram 2

I know that the main() definition is as shown below, and that argc is a counter, and argv is a pointer to a character array (I think this is right) containing the command lines.

int main(int argc, char *argv[]){
    return 0;
}

The question I have is, how do I convert the character 2 (which is my command line argument, it could be any number) to an int?

I've googled and a few things come across casting, which I believe is changing one data type to another, and I have tried:

int a = (int)(argv[1]);

which compiles, but with a warning saying "cast from pointer to integer of different size". It compiles, but then won't run.

I suspect the answer I need is simple, it's just beyond my knowledge at the moment.

CodePudding user response:

You are probably having issues as "argv[1]" really is a pointer to a character array. What you probably would want to do is use the "atoi" conversion function which will convert a string to an integer. Following is a proof-of-principle code snippet.

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

int main(int argc, char *argv[])
{
    int i;

    if (argc > 1)
    {
        i = atoi(argv[1]);
    }

    printf("i: %d\n", i);

    return 0;
}

Following is some sample terminal output.

@Una:~/C_Programs/Console/Args/bin/Release$ ./Args 144
i: 144

Give that a try.

  • Related