You are here:

C++/checking if a string consists of all numbers or not.

Advertisement


Question
Hello, I would like to know if there is a way to check if a string consists of all numbers of not.
I have already a bit of the source code but seems like there's an error in it.
Please reveiew it for me and see what's wrong.

#include <string.h>
#include <iostream.h>

int main(){


string str = "12345";


for( i = 0; i < strlen(str) - 1; i++) {
  for(int j = 0; j <= 9; j++) {
     if(atoi(&str[i]) == j) {
        cout << "yes!";
     }
  }
}


return 0;
}

Answer
When you say you want to check if a string contains a number, you need to have a strong idea of what a "number" is. Do you want a valid integer, which can include '-' and '+' as well as the numeric digits? Or do you want a valid floating-point number, which can also use 'e', 'E', '.', or even ',' depending on locale and whether the representation is scientific or floating-point. If you just want to make sure that all characters in a string are numeric digits, it's a trivial loop:

#include <cctype>
#incldue <string>

bool is_number(const std::string& s)
{
   for (int i = 0; i < str.length(); i++) {
       if (!std::isdigit(s[i]))
         return false;
   }

   return true;
}

int main()
{
   std::string str = "12345";

   if (is_number(str))
       std::cout<<"yes!"<<endl;
   else
       std::cout<<"no"<<endl;
}

The biggest problem with your code is that you're confusing the string class with C-style strings. strlen and atoi expect a pointer to const char, not an object of std::basic_string. Also, the way you call atoi is suspect. If you find yourself needing to use the address-of operator in a call to atoi, it's probably wrong.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Sandra Guth

Expertise

I can help with any questions concerning ISO standard C++, object oriented programming and design as well as algorithms and data structures.

Experience

I have nine years of programming experience with C++.

©2016 About.com. All rights reserved.