How to use stoul() In C++

In C++ to convert a string into a long integer, there is a function called stoul(). The stoul() function performs a string to unsigned long conversion. 

Syntax:

unsigned long stoul (const string&  str, size_t* idx = 0, int base = 10);

Parameters:

  • str: String object with the representation of an integral number.
  • idx: Pointer to an object of type size_t, whose value is set by the function to the position of the next character in str after the numerical value. This parameter can also be a null pointer, in which case it is not used.
  • base: Numerical base (radix) that determines the valid characters and their interpretation. If this is 0, the base used is determined by the format in the sequence. Notice that by default this argument is 10, not 0. 

Below is the C++ program to convert string to long using stoul():

C++




// C++ program to convert
// string to long using stoul()
#include <iostream>
using namespace std;
 
// Driver code
int main()
{
    char s1[] = "20";
    char s2[] = "30";
    unsigned long int n1 = stoul(s1);
    unsigned long int n2 = stoul(s2);
    unsigned long int res = n1 + n2;
    cout << res;
    return 0;
}


Output

50

The time complexity is O(1)

The auxiliary space is also O(1)

C++ Program For String to Long Conversion

In this article, we will learn how to convert strings to long in C++. For this conversion, there are 3 ways as follows:

  1. Using stol()
  2. Using stoul()
  3. Using atol()

Let’s start by discussing each of these methods in detail.

Example: 

Input: s1 = “20” 
           s2 = “30” 

Output: s1 + s2 
             long: 50

Similar Reads

1. Using stol()

In C++, the stol() function performs a string to long conversion....

2. Using stoul()

...

3. Using atol()

In C++ to convert a string into a long integer, there is a function called stoul(). The stoul() function performs a string to unsigned long conversion....

Contact Us