0

I'm writing a command line calculator. Each expression is provided by user must be separated by space (that's convention). For example: ./calc 2 + 5 * sin 45

The problem is when I try to get each expression i get also as arguments all files that are in the folder that I've complied the code...

Here is the code:

int main(int argc, char* argv[]) {
    double result;
    int i;
    printf("Number of arguments: %d\n", argc);

    for (i=0; i<argc; i++) {
        printf("Argument: %s\n", argv[i]);
    }

    //result = equation(argv, argc);
    //printf("Result is: %f", result);
    return 0;
}

And the output for that example expression is:

Number of arguments: 10
Argument: ./calc
Argument: 2
Argument: +
Argument: 5
Argument: calc
Argument: calculate.c
Argument: lab2
Argument: sin
Argument: 45

And my question is why there are calc calculate.c lab2 (of course the folder where this program is compiled contains all the three files). Should I compile it in separate folder? I tried that approach but still the 'calc' is there

ps. i'm using the gcc compiler: gcc calculate -o calc

3 Answers 3

6

This has nothing to do with your program, and everything to do with your shell.

Most shells expand *, the wildcard character, into all matching files. This includes UNIX shells like bash, and Windows' cmd.

There's nothing you can do about this; it's just how it works.

The alternative would be for your program to take one argument, which is a string containing the expression to be parsed. Of course, you would have to do the parsing, instead of the shell doing it for you. E.g.

./calc '2 + 5 * sin 45'

Note the single quotes. This prevents the shell from expanding anything inside. Your pgrogram then has argc == 2, where argv[1] == "2 + 5 * sin 45".

Sign up to request clarification or add additional context in comments.

Comments

3

This is due to the command line expansion of the * character (which matches all files in the current folder). Try quoting it like so:

./calc 2 + 5 '*' sin 45

or escaping it as follows:

./calc 2 + 5 \* sin 45

Best use a diffent character ..

Comments

2

The * character is a special character on most shells. In Linux, the shell interprets it as "everything in the current directory" and expands it before feeding it to the command. That's how you can use a command like this:

grep 'some string' *

The shell expands * to mean all files, so that statements searches for 'some string' in all files. In your case, when you want the shell to interpret * as a literal character, you should put it in quotes, or escape it with a \ character.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.