简体   繁体   English

(C++) 我如何限制这个计算器 arguments 的范围?

[英](C++) How do i limit the range of arguments for this calculator?

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")"你好,我正在尝试使用 Arguments 制作一个计算器,我遇到的一个问题是,每次我尝试使用不等式来限制输入范围时,程序都会失败。我不断收到此错误“操作数类型不兼容(“char *”和“整数”)“

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

You may want to convert the argument to an integer before checking the range.在检查范围之前,您可能希望将参数转换为 integer。

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.另一个注意事项是所有不超过-360653的整数都小于360653 ,所以你的情况看起来很奇怪。

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;
}

Check you have some args for safety then convert the char * to an int:检查您是否有一些安全参数,然后将 char * 转换为 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM