[Solved] Taking main argument [duplicate]


[Note: C does not have builtin string type. What C has is character array]

This is a very easy to solve problem. Here’s the code given, it uses stdlib‘s builtin atoi function to convert string to int:

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

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

    if (argc == 2) {
    
        char *var_str = argv[1];
        
        int variation = atoi(var_str);

        printf("variation: %d\n", variation);
    
    }
    else if (argc < 2) {
    
        printf("no agrument provided.\n");

    } else {

        printf("only one argument was expected. %d provided.\n", argc);
    }
    
    return 0;
}

Update (A more secure version using strtol):

As strtol is a better function to convert string to long int, than atoi, because of it’s error detecting utility, it’s better to use strtol in this regard. This practice is heavily enforced by user @klutt. I would like to thank her/him for advising me to include the code using strtol too. It is given below:

// a more secure version

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

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

    if (argc == 2) {
        char *var_str = argv[1];

        char *text = NULL;
        int base = 10; // default base

        errno = 0; // intializing errno

        long int variation = 0;
        variation = strtol(var_str, &text, base);

        // now on to error detection
        // full error trace
        if (var_str == text) {
            printf ("error: no number found\n");

        } else if (errno == ERANGE && variation == LONG_MIN) {
            printf ("error: underflow\n");

        } else if (errno == ERANGE && variation == LONG_MAX) {
            printf ("error: overflow\n");

        } else if (errno != 0 && variation == 0) {
            printf ("error: unknown error\n");

        } else if (errno == 0 && var_str && !*text) {
            printf ("variation: %ld\n", variation);

        } else if (errno == 0 && var_str && *text != 0) {
            printf ("variation: %d, but some text included: %s\n", variation, text);
        }

    } else if (argc < 2) {
    
        printf("no agrument provided.\n");

    } else {

        printf("only one argument was expected. %d provided.\n", argc);
    }
    
    return 0;
}

If you have any questions, ask me in comment…

14

solved Taking main argument [duplicate]