0

Working on a program that compares an argument to text in a file (my file being a dictionary containing a lot of english words).

Right now the application works only the strings match completely.

Wanted to know if there was a way to compare a partial string that is inputted to a complete string in the file and have it be a match. Example if the arg is ap, it'll match it to apple, application alliance ext.

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


int main ( int argc, char *argv[] ) {

    ifstream inFile;
    inFile.open("/Users/mikelucci/Desktop/american-english-insane");

    //Check for error

    if (inFile.fail()) {
        cerr << "Fail to Open File" << endl;
        exit(1);
    }

    string word;
    int count = 0;


    //Use loop to read through file until the end

    while (!inFile.eof()) {
        inFile >> word;
        if (word == argv[1]) {
            count++;
        }
    }

    cout << count << " words matched." << endl;

    inFile.close(); 
    return 0;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 1
    `ap` should match with `alliance`? Then just compare the first characters. Otherwise, [here](http://stackoverflow.com/questions/1878001/how-do-i-check-if-a-c-string-starts-with-a-certain-string-and-convert-a-sub)'s your duplicate. And that `eof` thing... don't do it and google why/what to do instead. – LogicStuff Dec 10 '16 at 23:17
  • std::string::compare() or std::regex - and don't loop on eof() - see https://latedev.wordpress.com/2012/12/04/all-about-eof/ for why –  Dec 10 '16 at 23:20
  • Maybe you are looking for the likeness via an algorythm like [the lenshtein-distance](https://en.wikipedia.org/wiki/Levenshtein_distance)? [Google has links](http://www.google.com/search?q=levenshtein+distance+c%2B%2B) –  Dec 10 '16 at 23:29

2 Answers2

3

If by "match" you mean "a string from file contains a string from the input" then you can use string::find method. In this case your condition would look like that:

word.find(argv[1]) != string::npos

If by "match" you mean "a string from file starts with a string from the input" then, again you can use string::find but with the following condition:

word.find(argv[1]) == 0

The relevant documentation is here.

Ardavel
  • 1,445
  • 1
  • 12
  • 23
0

Start by copying argv[1] into a string (not strictly necessary, but it makes the subsequent comparison a bit simpler):

std::string target(arg[1]);

Then use std::equal:

if (std::equal(word.begin(), word.end(), target.begin(). target.end()))

This form of equal (added in C++14) returns true if the shorter of the two sequences matches the corresponding characters at the beginning of the longer.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165