Home > Back-end >  (C ) How do i limit the range of arguments for this calculator?
(C ) How do i limit the range of arguments for this calculator?

Time:03-31

Hello i am trying to make a Calculator using Arguments and one issue i am having is that everytime i try and use inequalities to limit the range of inputs the program fails.I keep getting this error "operand types are incompatible ("char *" and "int")"

#include <iostream>
int main(int argc, char* argv[]) {    
// Range
if (argv[1] <= 360653 && argv[1] <= -360653) {
    cout << "error";
    return 0;}
else
   //Do stuff
}

CodePudding user response:

You may want to convert the argument to an integer before checking the range.

Also don't forget to check if the argument actually exists.

Another note is that all integers not more than -360653 are less than 360653, so your condition looks strange.

You may want this:

#include <iostream>
#include <cstdlib>
int main(int argc, char* argv[]) {
    if (argc < 2) {
        std::cout << "no argument\n";
        return 1;
    }
    int value = atoi(argv[1]); // TODO: use better function like strtol
    // Range
    if (value <= -360653 || 360653 <= value) {
        cout << "error\n";
        return 0;
    } else {
       //Do stuff
    }
    return 0;
}

CodePudding user response:

Check you have some args for safety then convert the char * to an int:

#include <iostream>
#include <cstdlib> // for atoi

int main(int argc, char* argv[]) {    
    if (argc > 1)
    {
        // Range
        int number = std::atoi(argv[1]);
        if (number >= 360653 || number <= -360653) { // note >= not <=, and || not && 
        cout << "error";
        return 0;
    }
    else {
        //Do stuff

    }
    // else maybe print a message
}
  •  Tags:  
  • c
  • Related