Simple calculator using command line with C++

后端 未结 5 445
遇见更好的自我
遇见更好的自我 2021-01-26 10:57

I\'m writing a project that we do simple calculator from command line. The users input in this format programname firstNumber operator secondNumber. Here what I

5条回答
  •  -上瘾入骨i
    2021-01-26 11:54

    The other answers are correct, but I'm going to pitch using strtod instead of atof in the name of Eris and because it's easier to check the input for correctness.

    char * endp;
    double firstNumber;
    if (argv[1][0] != '\0')
    { // input string is not empty 
        firstNumber = strtod (argv[1], &endp);
        if (*endp != '\0')
        { // number didn't end at the end of the string. String not a number.
            cout << "First number was not a number, dude." << endl;
            return 0;
        }
    }
    else
    {
        cout << "Can't do much without a number, dude." << endl;
        return 0;
    }
    

    With atof, the program can be called with "I'm the very model of a modern major-general" and produce results. Bad results, but results all the same.

    Oh, and warning on calling exit in C++. The program stops dead right there, and no destructors are called. No harm here, but not a good habit to get into.

提交回复
热议问题