Numeric Conversion Functions in C++
String in C++ Standard Library Simplified - Part 6
Forward: In this article, I explain some functions that convert strings to numbers in C++.
By: Chrysanthus Date Published: 25 Aug 2012
Introduction
Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.
The C++ cstdlib Header
You need the cstdlib header file to convert strings to numbers. Each of the functions here takes a string with constant content as argument. So the content of the string we want to convert to number should be made const. A char* pointer proceeded by the keyword const points to a string whose content is constant. A string literal in quotes has a constant content. In this part, functions (not methods) of the cstdlib header file are used. I will give you just two functions (there are others). Each of the functions here takes one argument. The string header file can be used for any string object that you want. However, the functions do not take string objects. So the string literal from any string object has to be obtained as a string with constant content, if you want the literal of the string object.
The atof Function
The syntax is
float atof(const char *nptr);
It converts a string with constant content (const char *nptr) to a number of type, float.
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
const char *strLPtr = "2504.368";
string str = strLPtr;
const char *ptrChar = str.c_str();
float number = atof(ptrChar);
cout << number;
return 0;
}
The first three statements are not necessary for the operation of the atof function. However, you will meet them in programming, in different forms, related to the atof function. You can use a string literal directly as argument to the atof function. The following code illustrates this (read and try it):
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
cout << atof("2504.368");
return 0;
}
The syntax is:
int atoi(const char *nptr);
It converts a string with constant content (const char *nptr) to a number of type, int. Try the following:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
cout << atoi("352");
return 0;
}
There are more functions on this topic; but for this simple tutorial we shall end here and continue in the next part of the series.
Chrys
Related Courses
C++ CourseRelational Database and Sybase
Windows User Interface
Computer Programmer – A Jack of all Trade – Poem