tags:

views:

114

answers:

4

Pretty simply question ... Is there any predefined function in Qt which can determine whether a string contains only a number ? .. with valid entries such as "28" and invalid entries such as " 28", "28 " and "2a8 .... ?

+5  A: 

Take a look on the QValidator and it's subclasses, if you are trying to validate input from the user.

If you are trying to convert the input in a string to a number, take a look in the methods such as toInt from the QString class.

cake
+1  A: 

Simplest is probably to check if the string contains any whitespace - if it does fail. Then use strtod and/or strtol to check for a valid number.

#include <string>
#include <cstdlib>
#include <cassert>

bool HasSpaces( const std::string & s ) {
    return s.find( ' ' ) != std::string::npos;
}

bool IsInt( const std::string & s ) {
    if ( HasSpaces( s ) ) {
        return false;
    }
    char * p;
    strtol( s.c_str(), & p, 10 );   // base 10 numbers 
    return * p == 0;
}


bool IsReal( const std::string & s ) {
    if ( HasSpaces( s ) ) {
        return false;
    }
    char * p;
    strtod( s.c_str(), & p );  
    return * p == 0;
}

int main() {
    assert( IsReal( "1.23" ) );
    assert( IsInt( "1" ) );
    assert( IsInt( "-1" ) );
    assert( IsReal( "-1" ) );
    assert( ! IsInt( "1a" ) );
    assert( ! IsInt( " 1" ) );
}

Note the above code on;y works for numbers in the numeric range of the C++ implementation - it won't work correctly for arbitrarily large integers, for example.

anon
+1  A: 

Well, I assume by number you mean Integer. You can go this way.

int QString::toInt ( bool * ok = 0, int base  = 10 ) const

From the documentation,

If a conversion error occurs, *ok is set to false; otherwise *ok is set to true.

So after calling the function, check for the value of ok. If it is true (i.e if the string can be converted into a number), then your string has just numbers.

If your number is a double, you can use this function.

double QString::toDouble ( bool * ok = 0 ) const

More documentation & examples can be seen here

Hope it helps..

liaK
A: 

well I agree the simplest way is to convert to a number using toInt() and related functions and checking the boolean parameter, but you can also do something like using qstring::at() and calling isdigit on the return value like this (looping over the string)

myString.at(i).isDigit() this will return true if the character at position i is a number so you can make a simple function that takes a string and returns true if al characters are digits

Olorin