问题描述:

How can I parse numbers like 0x345, 23423, 0172 (possibly also 0b001111) from strings?

I found the regular QString::toXXX functions but they take a base argument, but i want the base to be determined from the string in a way as it a C-Compiler would do.

I think there must be something present in Qt. But I only found the above mentioned or other method that explicitly take base (e.g. as stream manipulator).

Thank you in advance.

网友答案:

The QString::toXXX do what you want (except the binary representation):

If base is 0, the C language convention is used: If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.

So just use int i = s.toInt(NULL, 0);

网友答案:

As it turned out, you'd only want to do this for binary numbers.

You have to detect the base manually (by reading the prefixes), by either:

  • using QString::left, or
  • using regular expressions

and then doing QString:toXXX with that base.

相关阅读:
Top