проблемы с позицией argc при ссылке в коде - PullRequest
0 голосов
/ 14 января 2019

У меня проблема в том, что если в командной строке недостаточно аргументов, я хочу, чтобы программа запрашивала все значения. По какой-то причине это работает, когда я предоставляю 2 из 3 аргументов, но я хочу, чтобы это работало, если указан 1 или ни один из аргументов.

Мой код

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

    float areaOfcircle(float radius_circle)
    {
        float area_circle;
        area_circle = M_PI * radius_circle * radius_circle;

        return area_circle;
    }
    void resitance_current(float length, float area_circle, float voltage, float* resistance, float* current)
    {
        float resistivity;
        resistivity = 1.782*pow(10, -8);
        *resistance = ((resistivity*length) / area_circle);
        *current = (voltage / *resistance);
    }

    void radius_check(float radius)
    {
        if (radius <= 0)
        {
            printf("Radius cant be less than or equal to 0");
            exit(1);
        }
    }
    void voltage_check(float voltage)
    {

        if (voltage <= 0)
        {
            printf("Voltage cant be less than or equal to 0");
            exit(1);
        }
    }
    void length_check(float length)
    {
        if (length <= 0)
        {
            printf("Length cant be less than or equal to 0");
            exit(1);
        }
    }

    void validation(float radius, float voltage, float length)
{
    radius_check(radius);
    voltage_check(voltage);
    length_check(length);
}
    int main(int argc, char *argv[])
    {
        float radius, voltage, length, current, resistance;
        float length_u, length_l;
        //dumpargs(argc, argv);
        radius = atof(argv[1]);
        voltage = atof(argv[2]);
        length = atof(argv[3]);
        if (argc != 4)
        {
            printf("Not enough arguments supplied\n");
            printf("Enter the radius of wire : ");
            scanf("%f", &radius);
            radius_check(radius);
            printf("Enter the Voltage of circuit : ");
            scanf("%f", &voltage);
            voltage_check(voltage);
            printf("Enter the Length of Wire : ");
            scanf("%f", &length);
            length_check(length);
        }
        validation(radius, voltage, length);
        resitance_current(length, areaOfcircle(radius), voltage, &resistance, &current);
        printf("Resistance = %f , Current = %f\n", resistance, current);
        printf("\nEnter the Upper Length of Wire : ");
        scanf("%f", &length_u);
        printf("\nEnter the Lower Length of Wire : ");
        scanf("%f", &length_l);
        if ((length_l < 0) || (length_l >= length_u))
        {
            printf("\nImpossible for Lower Length < 0 or to be larger then Length Upper");
            exit(1);
        }
        else
        {
            for(length_l = length_l; length_l<=length_u; length_l++)
            {

                resitance_current(length, areaOfcircle(radius), voltage, &resistance, &current);
                printf("\nLength = %0.3f Resistance = %0.3f , Current = %0.3f", length, resistance, current);
                length = (length_l + 1);

            }
        }
        return 0;
    }

Как видно из кода "if (argc! = 4)", значения запрашиваются снова и снова, если они были переданы через командную строку. Я пытаюсь найти решение этой проблемы, так что, если бы программа была запущена из CMD самостоятельно, значения были бы запрошены, но если все значения были предоставлены, код работал бы до конца. За исключением аргумента argc, код работает как требуется.

Спасибо за любую помощь заранее

1 Ответ

0 голосов
/ 14 января 2019

Вы выходите за пределы, если аргументы переданы меньше чем 4.

Просто измените код, как показано ниже. Сначала проверьте количество переданных аргументов, затем получите доступ к argv.

    if (argc != 4) // or if (argc < 4)
    {
        printf("Not enough arguments supplied\n");
        printf("Enter the radius of wire : ");
        scanf("%f", &radius);
        printf("Enter the Voltage of circuit : ");
        scanf("%f", &voltage);
        printf("Enter the Length of Wire : ");
        scanf("%f", &length);
    }
    else {

        radius = atof(argv[1]);
        voltage = atof(argv[2]);
        length = atof(argv[3]);
    }
    radius_check(radius);
    voltage_check(voltage);
    length_check(length);

Также вам необходимо проверить возвращаемое значение scanf, Прочтите это, как проверить возвращаемое значение scanf .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...