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

Time:02-23

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

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related