首页 > 解决方案 > Taking main argument

问题描述

I have a problem with my code. I would like to know what the "variation" value is. But it always gives me extremely high or negative values. So when I type in terminal for example ./NAME 3 I end up with another number. How can i fix it?

#include <stdio.h>
#include <cs50.h>


int main(int argc, string argv[])
{
    int variation =  (int)argv[1];
    if (argc == 2)
    {

        printf("%i\n", variation);

        return 0;
    }

    else
    {
        return 1;
    }

}

标签: ccommand-line-argumentsmaincs50argv

解决方案


[注意:C没有内置string类型。有的是] C_character array

这是一个非常容易解决的问题。这是给出的代码,它使用stdlib's 内置atoi函数转换stringint

#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;
}

更新(使用更安全的版本strtol):

asstrtol是一个更好的转换stringlong int,的函数atoi,因为它是错误检测的utility,所以最好strtol在这方面使用。这种做法是由 user 严格执行的@klutt。我要感谢她/他建议我也包含使用的代码strtol。下面给出:

// 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;
}

如果您有任何问题,请在评论中问我...


推荐阅读