How to check if argv (argument vector) contains a char, i.e.: A-Z
Would like to make sure that argv only contains unsigned intergers
For example:
if argv[1] contained "7abc7\0" - ERROR
if argv[1] contains "1234\0" - OK
How to check if argv (argument vector) contains a char, i.e.: A-Z
Would like to make sure that argv only contains unsigned intergers
For example:
if argv[1] contained "7abc7\0" - ERROR
if argv[1] contains "1234\0" - OK
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;
}
Modified, of course, to operate on argv instead of cin.
This may not be exactly what you want though - run a few tests on it and check the output if you don't understand what it does.
bool isuint(char const *c) {
while (*c) {
if (!isdigit(*c++)) return false;
}
return true;
}
...
if (isuint(argv[1])) ...
Additional error checking could be done for a NULL c pointer and an empty string, as desired.
update: (added the missing c++)
How about this:
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
;
}
A much more flexible approach (ie: probably more than what you are asking for in your question) but is still very easy to use is using getopts which is part libc