BaloneyOs
BaloneyOs

Reputation: 317

C++ matching a specific string

I have a function here that checks a text file for the existence of a string. The problem I have right now is that it's checking for substrings, so if the file has the word "IronMan" and any part of that string will pass the check.

Here's my code for the function:

void UIFunctions::checkIfExists()
{
    while (!fin.eof())
    {
        getline(fin, line);
        if (line.compare(getFriendName()) == string::npos)
        {
            setExists(false);
            cout << getExistsErrorPrompt() << endl << endl;
            if (listAfterCheck == 1)
            {
                listUsers();
            }
            cout << endl;
            cout << endl;
            cout << getErrorPrompt();
        }
    }
}

I searched for solutions and read that line.compare (changed from line.find) is what I need to match entire strings but instead of accepting substrings (like line.find did) now it doesn't accept anything at all to pass the check.

Edit: Also the file that this function uses would look something like this:

Ironman Captain Thor

Upvotes: 0

Views: 81

Answers (2)

nwn
nwn

Reputation: 584

The problem is that you are assuming that compare returns the same value as find would. The compare function returns an integer with value:

  • 0 if the strings are equal
  • >0 if the compared string (in your case line) is lexicographically first
  • <0 if the comparing string (in your case getFriendName()) is lexicographically first

Therefore to check for an exact match, you would want:

if(line.compare(getFriendName()) == 0) {
    setExists(false);
    // ...
}

Comparing the result of compare with string::npos will never trigger since the magnitude of compare is the first differing character between your two strings.

Upvotes: 2

NathanOliver
NathanOliver

Reputation: 180585

std::basic_string::compare returns a value less than 0, 0 or more than 0. Since

if (line.compare(getFriendName()) == string::npos)

Is seeing if the return is the maximum value of the type of string::npos you more than likely will never trigger the if statement. If you only want to match a string exactly then you can use

if (line == getFriendName())

If instead you want to find any line that starts with getFriendName() then you want

if (line.find(getFriendName()) == 0) 

In the above find will only return 0 if the string starts with what you want.

Upvotes: 1

Related Questions