1

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
BrianDawe
  • 23
  • 6
  • 3
    The easiest way to convert a string to an int is to use [`atoi()`](https://cplusplus.com/reference/cstdlib/atoi/) – Jakob Lovern Sep 06 '22 at 22:30
  • The warning is because argv is an array of strings--a `char[][]`. C doesn't contain implicit string to int conversion as a language feature, so it tries to interpret the `char*` as an int, giving you the address of the first character. – Jakob Lovern Sep 06 '22 at 22:35
  • Do not forget to first check that there IS something there. `if( argc > 1) ...` – Fe2O3 Sep 06 '22 at 22:36
  • 2
    Does this answer your question? [How to convert a string to integer in C?](https://stackoverflow.com/questions/7021725/how-to-convert-a-string-to-integer-in-c) – ad absurdum Sep 06 '22 at 22:50
  • @JakobLovern -- note that `atoi` and friends are problematic conversion functions: they have undefined behavior when their input can't be represented as a value in the target type, and they don't report errors during conversion. `strtol` and friends are better choices. – ad absurdum Sep 06 '22 at 22:55
  • BrianDawe, if the command line had `abc` instead of `2`, what result would you like to see? – chux - Reinstate Monica Sep 06 '22 at 23:45

1 Answers1

1

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.

NoDakker
  • 3,390
  • 1
  • 10
  • 11
  • 3
    Note that `i` will be uninitialized if no command-line parameter is given. Accessing the value of an uninitialized variable, such as in a `printf()` call, is *undefined behavior*. – Remy Lebeau Sep 06 '22 at 22:39
  • `printf( "i: %d\n", atoi( argv[ 1 ] ) );` INSIDE the `if( )` block, perhaps? `:-)` – Fe2O3 Sep 06 '22 at 22:42
  • Yup. Good catch. – NoDakker Sep 06 '22 at 22:52
  • 2
    In principle, it's also a good idea to print a usage message to guide the user if the number of arguments is wrong. Similarly, it's not a good idea to ignore arguments, so the code should either complain when `argc != 2` or should iterate over all the arguments (only complaining when no arguments are supplied). Using `atoi()` means that `./Args 12dozen` or `./Args 1gross` will work (producing 12 and 1). Using `strtol()` or a similar function gives better control. Error messages should be printed on `stderr`. And, as it is just a learning exercise, I suspect my comments are OTT. – Jonathan Leffler Sep 06 '22 at 23:11
  • Thanks everyone for your help and suggestions. NoDakker that worked a treat thank you. Pointers are "fun" :D I'm sure ill get my head around it. And @JakobLovern I have made a note of your suggestion also and will look into it – BrianDawe Sep 06 '22 at 23:15
  • Fe2O3 Thanks and also Thanks Jonathan I have screen capped you're reply so that I can try and do just that better to learn the right way from the start :D – BrianDawe Sep 06 '22 at 23:22