PDA

View Full Version : best way to check for data type



timmu
3rd January 2012, 08:50
Hi,

I was wondering what would be the best way using Qt to check for the input data type. Data input is done using QTextStream. I'd like to know if each data entry is a) an integer, b) a floating number, or c) a string. What would be the fastest and most reliable way to tell that.

So far I've been doing it like this (but it is not elegant):


//string_in is the string to be tested
QString TestString = string_in; strcpy(string_in, TestString.toLocal8Bit().constData());
int TestInt = TestString.toInt();
float TestFloat = TestString.toFloat();

QString int_to_text; int_to_text.setNum(TestInt);
char int_to_string[999]; strcpy(int_to_string, int_to_text.toLocal8Bit().constData());

if(strcmp(string_in,int_to_string)==0) datatype=1; //entry is int (1)
else
{
QString float_to_text; float_to_text.setNum(TestFloat);
char float_to_string[999]; strcpy(float_to_string, float_to_text.toLocal8Bit().constData());
if(strcmp(string_in,float_to_string)==0) datatype=2;

else datatype=3; //entry is string (3)
}


Thanks!

pi88el
4th January 2012, 10:40
You can use the boost/lexical_cast to convert your string and catch a bad_lexical_cast if convertion failed. That would be more elegant.