1

My question is how to pass int arguments through argv[].

The form I want to use is the following: while the NTHREADS, and LETTER can be optional, the FILE1 must be provided.

./test [-t NTHREADS] [-l LETTER] FILE1

How can I handle this?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

2 Answers2

3

You can't. All arguments to main() are char* by definition. If you want you can convert them, but that's done at your own discretion. There are tools like getopt that make writing interfaces like this a lot easier, and they can be used to do conversion as necessary.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
tadman
  • 208,517
  • 23
  • 234
  • 262
  • Not quite right. For a freestanding environment, `main` can have any signature (and name). – too honest for this site May 05 '17 at 23:27
  • 3
    @Olaf: we discuss hosted environments only unless someone specifically points out they're working in a freestanding environment. There are so many caveats around freestanding environments that it would make everything unanswerable. Your comment is pointless nitpicking. Please remove it, and then flag this obsolete. – Jonathan Leffler May 05 '17 at 23:37
  • i resoved the problem now can i use optional and named parametre with main ? – Hiiro Procrastination May 06 '17 at 01:16
  • It's worth opening a new question that contains the code you wrote. This is a new problem. – tadman May 06 '17 at 01:26
  • i cant open a question until 24h new acount , but here is the problem my main fonction need optional and named argument the named one is a file this argument has to be ther in any situation how do i do it – Hiiro Procrastination May 06 '17 at 01:41
1

You can use either the atoi() function, which is available in the stdlib.h standard library, or for a more robust solution you can use strtol(), which is also in stdlib.h

Example:

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

int main( int numArgs, char **argList )
{
    int num, i;
    for( i = 0; i < numArgs; i++ )
    {
        fprintf( stdout, "\nArgument #%i (\"$s\") is %li as a number.", i, argList[i], strtol(argList[i], NULL, 10) );
    }

    return 0;
}
Will
  • 33
  • 1
  • 8