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
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.