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,
Pointers in C/C++ [Full Course]
#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 :
Frequently Asked:
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.