0

I need to read args given by the user. They would type something like ./main -3 word1 word2 word3... and so forth.

I need a way to parse the first argument given to determine if it's an integer or not. If it is then I need to snag that integer. Here is the code I have worked up thus far.

#include <stdio.h>

int main(int b, char** locations) {

    char determine = locations[1];
    return 0;
}

As far as I understand strtok() picks apart a string by an argument you give it. For example you can remove the space from a string that you know contains a string.

The problem is that in my situation the user can either enter a number or enter no number and I need to differentiate whether the first argument given is an integer or not. If it is then I need to be able to obtain the integer as a variable.

One thing that helps me though is that if the user is going to enter an integer then they have to use a - in front of it.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
itsMe
  • 51
  • 7
  • I don't believe so, the first argument can either be a string or string integer combo, so either its a string like "someString like this" or if the user gives an integer they have to use the "-" in front of the integer for example "-(somenumber)" – itsMe Feb 03 '21 at 05:43
  • This is not correct statement anyway `char determine = locations[1];` – IrAM Feb 03 '21 at 05:45
  • Command line args are given to you as seperate strings. So `./main -3 word1 word2` gives you strings in `locations[1]`, `locations[2]` and `locations[3]`. Then you can use the info in the linked post to check `locations[1]` which in the example will contain exactly `-3`. – kaylum Feb 03 '21 at 05:47
  • You can use[`strtol()`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html) (carefully) to do most of the work of finding out whether the string is an integer or not. You might need to check whether there are non-digits after it stops converting, but that's all. (See also [Correct usage of `strtol()`?](https://stackoverflow.com/q/14176123/15168) for more information.) – Jonathan Leffler Feb 03 '21 at 05:47
  • 1
    Note that it is conventional to call the arguments to `main()` by the names `argc` and `argv` — though some people use `ac` and `av`. Your code will be more readily recognizable if you use the standard names. It isn't formally wrong to use other names, but … You should check that `b > 1` before using `locations[1]` — using your nomenclature. – Jonathan Leffler Feb 03 '21 at 05:49
  • So first you'd determine if the **first** character in an argument is `'-'`? Right? After that it is correct usage of `strtol` from *2nd character* onwards – Antti Haapala -- Слава Україні Feb 03 '21 at 05:49
  • i appreciate your advice, i am only a junior in university at the moment so that will be helpful to know later on when i work for the industry – itsMe Feb 03 '21 at 05:54

0 Answers0