Assigning values to a variable

1

I have the following program:

#include <stdio.h>
int a,b;
int main(int argc,char *argv[]){
    int c;
    printf("%d",a+b);
    printf("%d",c);
    return 0;
}

How do I pass a value to the global or local variable via terminal? When I exit the program, I want it to return the sum immediately given a command via terminal, for example:

I compile the program:

cc exemplo.c -o exemplo

Then to do the output :

./exemplo < a=1 b=2
    
asked by anonymous 11.04.2018 / 20:28

2 answers

0

You need to get the array data from arguments that main() receives. Get each of the elements without getting the 0 which is the name of the executable.

As the argument comes as string , you need to do a conversion with strtol() .

There are a number of checks that would be good to do, such as whether the number of arguments needed, whether the number conversion worked, or what might be useful for the problem.

You do not need variables to display the sum. But if you're going to use variables for something else, do not make them global, it's hardly ever necessary.

You do not need this static variable, I just did this by limiting the ideone.

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

static char *argv[] = { "app", "123", "456" }; //gambiarra pra simular a passagem de argumento pela linha de comando

int main(/*int argc, char *argv[] */) {
    printf("Soma: %ld", strtol(argv[1], NULL, 10) + strtol(argv[2], NULL, 10));
}

See running on ideone .

    
11.04.2018 / 20:39
1

In its main function, argc represents the number of arguments being passed, while argv is an array with each argument. In your example, invoking ./exemplo 1 2 , would be 3 arguments (argc = 3), being:

argv [0]="example"

argv [1]="1"

argv [2]="2"

In this way, you can use them like this:

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

int a,b;
int main(int argc,char *argv[]){
    int c;

    // string to long(string, endptr, base)
    // Converte o argv de String para Inteiro
    a = strtol(argv[1], NULL, 10);
    b = strtol(argv[2], NULL, 10);

    printf("%d",a+b);
    printf("%d",c);
    return 0;
}

Test and give me feedback. I am without a C compiler at the moment, but I edit if something is out when I test.

    
11.04.2018 / 20:39