Check if a String can be converted to an int in C++

This tutorial will discuss about unique ways to check if a string can be converted to an int in C++.

Technique 1: Check if string can be converted to an integer

We can use the stoi() function to convert a string into an integer. If the string contains a valid integer i.e. digits only, then it will be successfully converted into an integer, otherwise it will throw an exception like invalid_argument or out_of_range. If we encounter any exception while converting a string to integer, using the stoi() function, then we can confirm that this string cannot be converted into an integer.

Let’s see the complete example,

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

// Check if string can be converted to an integer
bool isInt(const string& str)
{
    bool result = true;
    try
    {
        // Convert string to int
        int n = stoi(str);
    }
    catch (const invalid_argument& e)
    {
        result = false;
    }
    catch (const out_of_range& e)
    {
        result = false;
    }
    return result;
}

int main()
{

    string strValue = "123";

    // Check if a string can be converted to an int
    if (isInt(strValue))
    {
        cout << "Yes, string can be converted to an int" << endl;
    }
    else
    {
        cout << "No, String cannot be converted to an int" << endl;
    }

    return 0;
}

Output :

Yes, string can be converted to an int

Technique 2: Check if string can be converted to an integer

We can use the istringstream to convert a string to an integer. If the conversion is successful then we can confirm that string can be converted into an integer. Whereas, if conversion fails, then it means that this string cannot be converted into an integer or string is not holding a valid integer value.

Let’s see the complete example,

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

// Check if string can be converted to an integer
bool isInt(const string& str)
{
    int n;
    // create a istringstream oject from string
    istringstream istreamObject(str);
    // get an int value from stream
    istreamObject >> noskipws >> n;
    // Check if stringstream has reached its end and not failed
    return istreamObject.eof() && !istreamObject.fail();
}

int main()
{

    string strValue = "123";

    // Check if a string can be converted to an int
    if (isInt(strValue))
    {
        cout << "Yes, string can be converted to an int" << endl;
    }
    else
    {
        cout << "No, String cannot be converted to an int" << endl;
    }

    return 0;
}

Output :

Yes, string can be converted to an int

Summary

Today we learned about several ways to check if a string can be converted to an int in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top