如何检查argv(参数向量)是否包含char,即:A-Z
想确保argv只包含无符号的整数
例如:
if argv[1] contained "7abc7\0" - ERROR
if argv[1] contains "1234\0" - OK
答案 0 :(得分:5)
bool isuint(char const *c) {
while (*c) {
if (!isdigit(*c++)) return false;
}
return true;
}
...
if (isuint(argv[1])) ...
可以根据需要对NULL c指针和空字符串进行附加错误检查。
更新 :(添加了缺少的c ++)
答案 1 :(得分:1)
这个怎么样:
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
;
}
答案 2 :(得分:0)
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进行操作。
这可能不是你想要的 - 对它运行一些测试并检查输出,如果你不明白它的作用。
- 亚当
答案 3 :(得分:0)
一种更灵活的方法(即:可能比您在问题中要求的更多)但仍然非常容易使用getopts,这是libc的一部分