Skip to content

Commit 8eafee5

Browse files
add support for negative integer
1 parent b16c40d commit 8eafee5

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

string_is_number.cpp

+7-1
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,18 @@ using namespace std;
55

66
//https://stackoverflow.com/questions/4654636/how-to-determine-if-a-string-is-a-number-with-c
77

8+
//support positive and negative integer
89
bool is_number(const std::string& s){
9-
return !s.empty() && s.find_first_not_of("0123456789") == std::string::npos;
10+
if(s.empty()) return false;
11+
if(s.size() > 1 && s[0] == '-' && s.find_first_not_of("0123456789", 1) == std::string::npos) return true;
12+
return s.find_first_not_of("0123456789") == std::string::npos;
1013
};
1114

1215
int main() {
1316
cout << is_number("123") << endl; //1
17+
cout << is_number("-123") << endl; //1
18+
cout << is_number("-123abc") << endl; //0
19+
cout << is_number("-") << endl; //0
1420
cout << is_number("abc") << endl; //0
1521
cout << is_number("123abc") << endl; //0
1622
return 0;

0 commit comments

Comments
 (0)