How come this doesnt work?
I wrote some code that tries to extract an integer 100 out of this string:
"AB,SH#100 \r\n\0"
but the toInt() always fails; i.e. 0 is returned from toInt(). Note that the original data came in from QByteArray(). I currently use append() to convert from QByteArray to QString.
As a separate question, is there a better way to convert QByteArray to QString than QString::append()?
Code:
test.append( bte );
tmp[0].remove( 0, 3 );
int value = test.toInt();
Thanks!
Re: How come this doesnt work?
If you remove the three characters from the beginning, you still have the whitespaces and 0 at the end, so toInt() will fail.
Re: How come this doesnt work?
Why not just use QRegExp?
Re: How come this doesnt work?
can somebody post the solution in code?
Re: How come this doesnt work?
What is exactly that you want? You have to describe a general case and not a single example string.
Re: How come this doesnt work?
[Quote]
I wrote some code that tries to extract an integer 100 out of this string:
"AB,SH#100 \r\n\0"
[/quoute]
That's exactly what I want. Just try extracting it. Note to wyota: toInt() doesnt fail even if you have 100 spaces after SH#100
Re: How come this doesnt work?
Quote:
Originally Posted by
ShaChris23
Quote:
I wrote some code that tries to extract an integer 100 out of this string:
"AB,SH#100 \r\n\0"
That's exactly what I want. Just try extracting it.[/QUOTE]
I doubt that's what you want...
If you don't tell us what are the rules of extraction in general way, we can't possibly give you code (other than I have given above) to do it. You said "extract 100", so return "100" seems a fine way to do it.
Re: How come this doesnt work?
Hi,
Thanks for all the inputs. How about this:
A string contains many fields. Each field starts with a 2 ASCII characters followed by the # sign.
Each field is delimited by a comma.
The last field is terminated by "\r\n"
We need to extract the number ( int or float ) after the # sign.
e.g. "DV#1200.03,AB#34,SH#100\r\n\0"
So for example, if a user is interested in the field "SH", he has to
Extract the SH field out,
Chop off first 3 characters
Convert the remaining string to be a number.
I hope this is helpful. I might be wrong here...but I think there's a bug in the Qt's QstringList::filter() method.
Thanks!
Re: How come this doesnt work?
I'd do:
Code:
if(expected.size()>2 || str.size()<4) return 0;
static QRegExp rx
("([A-Z][A-Z])#([0-9]*\\.?[0-9]+)");
if(!rx.exactMatch(cmd))
continue;
if(rx.cap(1)==expected)
return rx.cap(2).toFloat();
}
}
QString str
= "DV#1200.03,AB#34,SH#100\r\n\0";
float val = extractCmd(str, "SH");