C++ Program to Implement atol Function

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.

  1. /*
  2.  * C++ Program to Implement atol Function
  3.  */
  4. #include <iostream>
  5. #include <cctype>
  6. #include <string>
  7.  
  8. /* Function converts string to integer */
  9. int atol(std::string s)
  10. {
  11.     int num = 0;
  12.     std::string::const_iterator i;
  13.  
  14.     for (i = s.begin(); i != s.end(); i++)
  15.     {
  16.         if (*i == ' ' || *i == '\t' || isalpha(*i))
  17.             continue;
  18.         else
  19.             break;
  20.     }
  21.     if (i == s.end())
  22.         return -1;
  23.     for (std::string::const_iterator j = i; j != s.end(); j++)
  24.     {
  25.         if (isdigit(*j))
  26.             num = num * 10 + (*j - '0');
  27.         else
  28.             break;
  29.     }
  30.     return num;
  31. }
  32.  
  33. int main()
  34. {
  35.     std::string s;
  36.     int num;
  37.  
  38.     std::cout << "Enter a numerical string : ";
  39.     std::cin >> s;
  40.     num = atol(s);
  41.     if (atol(s) >= 0)
  42.         std::cout << "The Numerical Value is  : " << num << std::endl;
  43.     else
  44.         std::cout << "No numerical digit found " << std::endl;
  45. }

$ 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
advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations