【问题标题】:Simple way to validate command line arguments验证命令行参数的简单方法
【发布时间】:2009-02-19 09:55:47
【问题描述】:

如何检查 argv(参数向量)是否包含字符,即:A-Z

希望确保 argv 仅包含无符号整数

例如:

if argv[1] contained "7abc7\0" - ERROR

if argv[1] contains "1234\0" - OK

【问题讨论】:

  • @stefant:添加标题为:windows的标签
  • 应该做的!下次会做:)
  • 不:最好这样做 - 因为一些开发人员可能不清楚什么平台 - linux/windows 等。只需“编辑”然后为标签写“windows”...
  • 哦,不知道你能做到。谢谢。

标签: c++ visual-studio-2008


【解决方案1】:
 bool isuint(char const *c) {
   while (*c) {
     if (!isdigit(*c++)) return false;
   }
   return true;
 }

 ...
 if (isuint(argv[1])) ...

可以根据需要对 NULL c 指针和空字符串进行额外的错误检查。

更新:(添加了缺少的c++)

【讨论】:

  • 不错,我知道一定有办法。
  • 那不需要 c++ 吗? while (*c) { if (!isdigit(*c++)) ... }(没有双关语!)
  • 已添加。谢谢你的收获。
【解决方案2】:

这个怎么样:

const std::string numbers="0123456789";

for(int i=1; i<argc; i++) {
  if(std::string(argv[i]).find_first_not_of(numbers)!=std::string::npos)
    // error, act accordingly
    ;
}

【讨论】:

    【解决方案3】:

    http://www.dreamincode.net/code/snippet591.htm

    #include <iostream>
    #include <limits>
    
    using namespace std;
    
    int main() {
      int number = 0;
      cout << "Enter an integer: ";
      cin >> number;
      cin.ignore(numeric_limits<int>::max(), '\n');
    
      if (!cin || cin.gcount() != 1)
        cout << "Not a numeric value.";
      else
        cout << "Your entered number: " << number;
      return 0;
    }
    

    修改后,当然是对 argv 而非 cin 进行操作。

    这可能不是您想要的 - 如果您不明白它的作用,请对其运行一些测试并检查输出。

    -亚当

    【讨论】:

      【解决方案4】:

      使用 getopts 是一种更灵活的方法(即:可能比您在问题中要求的更多)但仍然非常易于使用,这是 libc 的一部分

      【讨论】:

      • @hharez: 但是不是标准的 C++ 吗?
      • 您在哪个平台上工作?如果你有 gnu libc 那么它就可以工作了。
      • Windows (Win32) - 在 C (linux) 编程时我倾向于使用它
      • 我不相信 gnu libc 可用于 Win32 是吗?如果没有,那么除非有等价物,否则它不可用,但对于 linux c 或 c++ 开发,它肯定存在
      • 不,不是。但是还有其他选择 - 请参阅:codeguru.com/forum/showthread.php?t=393293(酷!:))
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      相关资源
      最近更新 更多