This is not a C++ question, but I was wondering how does the computer (or mobile phone) know how much battery power it has got left? How can it measure this so accurately to the nearest percent?
As for how it is done in the hardware: it measures voltage across the battery terminals. Every battery has at least two voltage levels defined by the manufacturer: the minimum voltage level (0% charged) and the maximum voltage level (100% charged). While the battery discharges, the voltage across its terminals drops. So if the voltage is close to the minimum level, the system knows the battery is almost discharged. Typical voltage levels for Li-Ion cells are: min: 2.7 V / cell, max: 4.1 V / cell.
Additionally the Li-Ion batteries have a critical minimum voltage level, which is slightly below 0% charged. If voltage ever drops below that critical level, because you left the battery without charging for too long the internal circuitry of battery disconnects the battery from the terminals and refuses to charge it (because it would be possibly dangerous; such battery appears to be dead - but service usually can bring it back to life, if only the battery hasn't been left for too long in this "undercharged" state).