Home > OS >  Function find() works incorrect
Function find() works incorrect

Time:10-14

My task is to check if a number contains 8 or not. I've converted the number into a std::string and have used its find() method. But it only works with a number which starts with 8, for example 8, 81, 881, etc. For numbers like 18, 28, etc, it doesn't work.

#include <iostream>
#include <math.h>
#include <string>

using namespace std;

unsigned long long g = 0;


int main()
{
    string str;
    cin >> str;
    int f = stoi(str);
    string eig = "8";
    for (int a = 1; a <= f; a  )
    {
        string b = to_string(a);
        if (b.find(eig) != size_t() && b.rfind(eig) != size_t())
        {
            cout << "It worked with " << b << "\n";
            g  ;
        }
        
    }
    cout << g;
}

CodePudding user response:

You are using std::string::find() and std::string::rfind() incorrectly. They do not return size_t() if a match is not found. They return std::string::npos (ie size_type(-1)) instead. size_t() has a value of 0, so find(...) != size_t() will evaluate as true if no match is found at all (-1 != 0), or any character other than the first character is matched (>0 != 0). This is not what you want.

Also, your use of rfind() is redundant, since if find() finds a match then rfind() is guaranteed to also find a match (though just not necessarily the same match, but you are not attempting to differentiate that).

Try this:

#include <iostream>
#include <string>
using namespace std;

unsigned long long g = 0;

int main()
{
    int f;
    cin >> f;
    for (int a = 1; a <= f; a  )
    {
        string b = to_string(a);
        if (b.find('8') != string::npos)
        {
            cout << "It worked with " << b << "\n";
              g;
        }        
    }
    cout << g;
}

CodePudding user response:

#include <iostream>
#include <string>
#include <cassert>

int main(int argc, char **argv) {
    auto s = std::to_string(1234567890);
    assert(s.find('8') != std::string::npos);
    return 0;
}

Is this what you want?

  • Related