vendredi 7 août 2020

Asterisk in C++ console lists all files in folder, why?

So I wanted to create a simple console calculator that'd take arguments via the int main(int argc, char ** argv) function. It works for regular examples, but trying multiplication with '*' started giving me way too many arguments listed in argv[], so I tinkered around and figured out it was listing all the files in the folder when '*' was used, supposedly for multiplication. I turned the if statement to always be true for debugging. I didn't find anything wrong with cerr, although I could've used the try-catch block.

I looked around the internet to see the reason for that, and I found that the asterisk can be used as some sort of wildcard to look for files in the folder, pretty similar, but not exactly what I was looking for. Thoughts?

Source code:

#include <iostream>
#include <string>

using namespace std;
int main(int argc, char ** argv)
{
    cout << "Argument count: " << argc << endl;
    if(true) // argc != 4
    {
        int i(0), j(0);
        while(argv[i])
        {
            j = 0;
            while(argv[i][j])
            {
                cout << argv[i][j];
                ++j;
            }
            cout << endl;
            ++i;
        }
    }
        //cerr << "Inadequate amount of arguments! " << argc;
    else
    {
        double num1, num2;
        try
        {
            num1 = stoi(argv[1]), num2 = stoi(argv[3]);
        }
        catch(exception e)
        {
            cout << "Unable to transform to integer.\n";
            return -1;
        }
        char op = *argv[2];
        switch(op)
        {
            case '+': cout << num1 + num2; break;
            case '-': cout << num1 - num2; break;
            case '*': cout << num1 * num2; break;
            case '/': cout << num1 / num2; break;
            default: cout << "Invalid operator.";
        }
    }

}

Aucun commentaire:

Enregistrer un commentaire