Compare a string and int in C++

This tutorial will discuss about unique ways to compare a string and int in C++.

Table Of Contents

Technique 1: Using the std::to_string() function

To compare a string with an int value, we can first convert the int value to string, and then we can use the == operator of string class to compare two string objects. To convert an int to string, we can use the std::to_string() function. It accepts an int value as an argument, and returns a string value containing the digits in provided int value.

Once int is converted to a string value, then we can compare it with another string using the == operator.

Let’s see the complete example,

#include <iostream>
#include <string>

int main()
{
    std::string strValue = "674";
    int number = 674;

    // Convert integer to string
    // and compare with string
    if (std::to_string(number) == strValue)
    {
        std::cout << "String and integer are equal \n";
    }
    else
    {
        std::cout << "String and integer are NOT equal \n";
    }

    return 0;
}

Output :

String and integer are equal

Technique 2: Using the stoi() function

To compare a string with an integer, first we need to convert the string into an integer. For that, we can use the std::stoi() function from header file <string>. It accepts a string as an argument, and interprets the string contents as an integer number. It converts the given string to int, and returns the int value. Once we have converted a string to int, then we can compare it with another int value.

Let’s see the complete example,

#include <iostream>
#include <string>

int main()
{
    std::string strValue = "674";
    int number = 674;

    // convert string to integer
    // and compare with integer
    if (std::stoi(strValue) == number)
    {
        std::cout << "String and integer are equal \n";
    }
    else
    {
        std::cout << "String and integer are NOT equal \n";
    }

    return 0;
}

Output :

String and integer are equal

Summary

Today we learned about several ways to compare a string and 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