Question

I'm writing a C program that accepts a list of unsigned long long numbers as input from the command line. How do I parse them and store in an array? It seems that strtoull might help, but how do I use it?

Here is my code:

#include<stdio.h>

main (int argc, char *argv[])
{
  unsigned long long M[1000];
  int i;
  printf("length: %d\n", argc - 1);
  for(i = 1; i < argc; i++) {
    M[i] = strtoull(argv[i], NULL, 10);
    printf("%llu\n", M[i]);
  }
  return 0;
}

It works when parameters are small, but when I enter a huge number (say, 123456789012345), it is not parsed correctly. What am I doing wrong?

Était-ce utile?

La solution

An easy approach is to use sscanf() on argv[i] with %llu to parse unsigned long long integers. Here's some sample code:

#include <stdio.h>

int main(int argc, char *argv[]) {
    unsigned long long example;
    int i;
    for (i = 1; i < argc; i++) {
        sscanf(argv[i], "%llu", &example);
        printf("Argument: %llu\n", example);
    }
    return 0;
}

You can use strtoull as well, in fact, I think scanf() uses it internally. Beware of overflows though, scanf() is not very well behaved with setting errno in appropriate occasions. I've had some problems with it. But you should be cool with unsigned long long, you really need a very big number to cause overflow.

Autres conseils

Yes, you can use strtoull. Here's an example framework:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
// include other headers as needed...


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

    // If there are no command line parameters, complain and exit
    //
    if ( argc < 2 )
    {
        fprintf( stderr, "Usage: %s some_numeric_parameters\n", argv[0] );
        return 1;
    }

    for ( i = 1; i < argc; i++ )
    {
        big_value = strtoull( argv[i], NULL, 10 );

        if ( errno )
        {
            fprintf( stderr, "%s: parameter %s: %s\n", argv[0], argv[i], strerror(errno) );
            return 2;
        }

        // Do some stuff with big_value

        ...
    }

    return 0;
}

Just remember that command line arguments are all strings. If you need to convert any to numbers (integer or real), then look at the man pages for the following functions:

int atoi(const char *nptr);
long atol(const char *nptr);
long long atoll(const char *nptr);
double atof(const char *nptr);
long int strtol(const char *nptr, char **endptr, int base);
long long int strtoll(const char *nptr, char **endptr, int base);
double strtod(const char *nptr, char **endptr);
float strtof(const char *nptr, char **endptr);
long double strtold(const char *nptr, char **endptr);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top