Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare number in a string with length of the string?

I’m new at programming and I’m trying to make a code that checks if a number inside of a string equals to the length of a string. I don’t understand why it doesn’t work. Can somebody explain what’s wrong with my code?

#include <iostream>

using namespace std;

int main()
{
  string str;
  cin >> str;

  int length = str.length();
  
for (int i = 0; i < str.size(); i++)
{   
    if (('0'<str[i])&&(str[i]<='9'))
    {
        cout<<"the length is: "<<length<<endl;
        cout<<"the num is: "<<str[i]<<endl;
        cout<<"the current string is: "<<str<<endl;
        if (length == str[i])
        {
            cout<<"yes"<<endl;
        }
        else
        {
            cout<<"no"<<endl;
        }
    }           
}
    return 0;
}

Here is an output:

aa5aa
the length is: 5
the num is: 5
the current string is: aa5aa
no

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You forgot to parse the value of the character into an actual integer:

#include <iostream>

using namespace std;

int main()
{
    string str;
    cin >> str;

    int length = str.length();
    int number = 0;

    for (int i = 0; i < str.size(); i++)
    {
        int a = 1;
        if (('0' < str[i]) && (str[i] <= '9'))
        {
            number = str[i] - '0';
            cout << "the length is: " << length << endl;
            cout << "the num is: " << str[i] << endl;
            cout << "the current string is: " << str << endl;
            if (length == number)
            {
                cout << "yes" << endl;
            }
            else
            {
                cout << "no" << endl;
            }
        }
    }
    return 0;
}

str[i] represents a character, not an integer. The actual numerical code value of character ‘0’ is not the same as the value of the number 0. Also, this is a crude way of converting character digits into integer values, but it does happen in real code in the wild so it’s a common enough trick to know.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading