How to convert a string to a floating-point number in C++ (11558)
The information in this article applies to:
- Microsoft C for MS-DOS
- Microsoft C for OS/2
- Microsoft Visual C++ 1.0
- Microsoft Visual C++ 1.5
- Microsoft Visual C++ 1.51
- Microsoft Visual C++ 1.52
- Microsoft Visual C++ 2.0
- Microsoft Visual C++ 2.1
- Microsoft Visual C++ 4.0
- Microsoft Visual C++, 32-bit Enterprise Edition 5.0
- Microsoft Visual C++, 32-bit Enterprise Edition 6.0
- Microsoft Visual C++, 32-bit Professional Edition 5.0
- Microsoft Visual C++, 32-bit Professional Edition 6.0
- Microsoft Visual C++, 32-bit Learning Edition 6.0
- Microsoft Visual C++ .NET (2002)
- Microsoft Visual C++ .NET (2003)
- Microsoft Visual C++ 2005 Express Edition
This article was previously published under Q11558 SUMMARY In an application developed with Microsoft C or C/C++, the
sscanf() function is a good alternative to the atof() function to convert a
string of digits into a floating-point number. If a string does not represent a
valid number, atof() returns the value zero; sscanf() returns more useful error
information. The application can use the error value from sscanf() with the
matherr() function to perform error handling. The atof() function does not call
matherr() unless an actual math exception occurs. The text below
presents two recommended methods to convert a string to a floating-point
number.
- Validate the string to convert prior to calling the atof()
function. Make sure that the string does not contain any non- numeric
characters and that the decimal point and sign characters are in the correct
locations.
- Use the sscanf() function. It is slower than the atof()
function, but it provides better information when an error occurs.
Modification Type: | Major | Last Reviewed: | 12/9/2005 |
---|
Keywords: | kbHOWTOmaster KB11558 kbAudDeveloper |
---|
|