Skip to content

Commit 15999ae

Browse files
author
Jesse
committed
added support for negative arguments
1 parent 0f25ffb commit 15999ae

2 files changed

Lines changed: 22 additions & 3 deletions

File tree

argparse.h

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,10 @@ class ArgumentParser {
9292
}
9393
};
9494
for (int i = 1; i < argc; i++) {
95-
if (std::strlen(argv[i]) == 0) {
95+
size_t slen = std::strlen(argv[i]);
96+
if (slen == 0) {
9697
continue;
97-
} else if (argv[i][0] == '-') {
98+
} else if (slen >= 2 && argv[i][0] == '-' && !isnumber(argv[i], slen)) {
9899
push_arg();
99100
if (i == argc - 1) {
100101
name = &(argv[i][1]);
@@ -220,6 +221,24 @@ class ArgumentParser {
220221
_trim(s, f);
221222
return s;
222223
}
224+
static inline bool isnumber(const char *arg, size_t len) {
225+
if (std::isdigit(arg[0])) {
226+
return true;
227+
} else if (len >= 2) {
228+
if (arg[0] == '-') {
229+
if (std::isdigit(arg[1])) {
230+
return true;
231+
} else if (len >= 3) {
232+
if (arg[1] == '.') {
233+
if (std::isdigit(arg[2])) {
234+
return true;
235+
}
236+
}
237+
}
238+
}
239+
}
240+
return false;
241+
}
223242

224243
std::string _desc;
225244
std::string _bin;

example.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ int main(int argc, char* argv[]) {
4848
auto v = parser.getv<double>("v");
4949
std::cout << "v: ";
5050
std::copy(v.begin(), v.end(), std::ostream_iterator<double>(std::cout, " "));
51-
double sum;
51+
double sum = 0;
5252
for (auto& d : v) sum += d;
5353
std::cout << " sum: " << sum << std::endl;
5454
auto f = parser.getv<std::string>("files");

0 commit comments

Comments
 (0)