How to pass values via terminal to a program function

1
#include <stdio.h>
#include <string.h>
void soma(int a,int b);
int main(int argc,char *argv[])
{
    printf("A soma=");
    return 0;
}

void soma(int a,int b){
    printf("%d\n",a+b);
}

How do I pass the values via terminal to the parameters of the function soma() ?

Compile:

cc exemplo.c -o exemplo

Run (does not work):

./exemplo < soma 3 4
    
asked by anonymous 11.04.2018 / 21:57

1 answer

1

According to the previous answer, I think this is what you want:

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

int soma(int a, int b) {
    return a + b;
}

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

But if you want to do the separate printing (I would not do it, but I would not even have this helper function too:

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

void soma(int a, int b) {
    printf("%d\n", a + b);
}

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

So it would make a little more sense:

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

int soma(char *primeiro, char *segundo) {
    return (int)strtol(primeiro, NULL, 10) + (int)strtol(segundo, NULL, 10));
}

int main(int argc, char *argv[]) {
    printf("Soma: %d", soma(argv[1], argv[2]));
}

You should not pass the "sum". If the intention is to call the function according to the text, and is not in the question, then it complicates a little, or a lot, depending on the technique required.

    
11.04.2018 / 22:04