This C++ Program which implements atol function which converts a C++ string to an integer value. The function atol( ) skips any trailing blanks and alphabets and if the string iterator has reached the end of the string, a negative value is returned to indicate that no digit is present in the string else the iterator goes through the remaining string until a non-digit character is encountered.
Here is source code of the C++ program which implements atol function which converts a C++ string to an integer value. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/** C++ Program to Implement atol Function*/#include <iostream>#include <cctype>#include <string>/* Function converts string to integer */int atol(std::string s)
{int num = 0;
std::string::const_iterator i;
for (i = s.begin(); i != s.end(); i++)
{if (*i == ' ' || *i == '\t' || isalpha(*i))
continue;
elsebreak;
}if (i == s.end())
return -1;
for (std::string::const_iterator j = i; j != s.end(); j++)
{if (isdigit(*j))
num = num * 10 + (*j - '0');
elsebreak;
}return num;
}int main()
{std::string s;
int num;
std::cout << "Enter a numerical string : ";
std::cin >> s;
num = atol(s);
if (atol(s) >= 0)
std::cout << "The Numerical Value is : " << num << std::endl;
elsestd::cout << "No numerical digit found " << std::endl;
}
$ g++ main.cpp $ ./a.out Enter a numerical string : 956 The Numerical Value is : 956 $ ./a.out Enter a numerical string : nonumber No numerical digit found
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
👉 For weekly programming practice and certification updates, join
Sanfoundry’s official WhatsApp & Telegram channels