-1

I was trying to find an elegant way to check if a string is a number. Then I was very surprised that C++ doesn't have an off-the-shelf function for that. Mybe I missed somthing that's why I didn't know.

I found one solution I like:

With C++11 compiler, for non-negative integers I would use something like this (note the :: instead of std::):

bool is_number(const std::string &s) {
  return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit);
}

But here I can't why it only works when there is :: before the isdigit. what does the :: do here?

Alan Birtles
  • 27,579
  • 4
  • 25
  • 50
BigTree
  • 21
  • 1
  • 4
  • 1
    It refers to the top/global namespace. If it doesn't work without it then you must have used that symbol in the current namespace. – freakish May 26 '22 at 06:06
  • 1
    The duplicates I linked are about `tolower`/`toupper`, but the exact same reasoning applies here to `isdigit`. – user17732522 May 26 '22 at 06:11

0 Answers0