在C ++中,我如何验证某些条件是否得到满足

时间:2014-04-06 07:23:51

标签: c++

我正在学习编码,我想做以下事情:

用户通过CMD Ex运行程序:

cd C:\ Program.exe P1 P2

该计划将完成其目的。但是我想验证,如果用户做了以下某些响应:

P1 =不是数字,或者+, - ,e,E是argv [1]中返回“错误”的第一个或最后一个字符。 P2 =第一个字符不是X而第二个字符小于2或大于16.这将返回响应“错误”

干杯

1 个答案:

答案 0 :(得分:1)

您可以轻松检查您的参数,因为它们只是字符串。将结果存储为std :: string允许您执行许多操作来测试输入。我对以下代码进行了大量评论,以帮助您理解检查。

每次发生错误时,都会使用fprintfstderr打印错误消息。您应始终将错误打印到此流而不是打印到stdout。这是因为用户仍然可以看到标准错误而不会干扰存储程序输出的内容。

如果程序在检查期间没有返回,那么您的程序可以在您知道输入正常的情况下运行。

#include <string>

int main (int argc, char *argv[]) {
    //Validate
    //If incorrect number of arguments, print error
    if (argc != 3) { //3 as program name is argument, ie argv[1]
        fprintf(stderr, "Not enough arguments");
        return 1; 
    } else { //Check arguments
        //Store arguments as strings to allow easy operations
        std::string p1 = argv[1];
        std::string p2 = argv[2];

        //Check P1
        if (! (p1.find_first_not_of( "0123456789" ) == std::string::npos) //if p1 is not made of 0-9
            && (p1.front() != '+' ) && (p1.front() != '-' ) //and the front char of p1 is none of the allowed characters
            && (p1.front() != 'e' ) && (p1.front() != 'E' ) ) //...then we have an error
        {
                fprintf(stderr, "Not a digit, or a +,-,e,E are the first or last character");
                return 1; 
        }


        //Check P2
        std::string numeral = p2.substr(1, p2.length()); //store everything but first char into new string
        int n = strtol(numeral.c_str(), NULL, 10); //use strtol to convert this to a number

        if (p2.front() != 'X' //if front is not X, we have error
            ||  !numeral.find_first_not_of( "0123456789" ) == std::string::npos //or if substring is not a number, we have an error
            || (n < 2 || n >16) ) //or if n is either less than 2 or greater than 16, we have an error
        {
            fprintf(stderr, "The first character is not X and the second character is less than 2 or greater than 16");
            return 1; 
        }


    } 

    //program body here....

    return 0;
}