简体   繁体   中英

Searching through a text files for a certain word C++

I'm trying to create a searchable recipe database by ingredient for a project. I'm trying to create the for loop that goes through the string vector (which has each ingredient saved to it) and search through the file and compare them. Right now, I just want it to output "Hello!" if theres a match. With all my fiddling, theres either 100 Hello!s (definitely not right) or none. Here's the code:

int main()
{
int y;
cout << "Hello! Welcome to Abby's Recipe Calculator." << endl << endl;
cout << "Please select an option: 1 to search by ingredient or 2 to browse recipes..." << endl;
cin >> y;

vector <string> ingreds;
ingreds.reserve(4); 

if (y == 1)
{
    ingredientvector(ingreds); // calls function to fill vector w/ ingredients
}
//else if (y == 2)
//{
//call recipe function... 
//}

Search x1(ingreds); //assigns ingredients to object vector

recipesearch(x1.getingreds());

system("pause");
return 0;
}

void ingredientvector(vector<string>& x)
 {
cout << "SEARCH BY INGREDIENT" << endl;
cout << "Please enter up to three ingredients... " << endl;

for (int i = 0; i < 4; i++)
{
    x.push_back("  ");
    getline(cin, x[i]);
    if (x[i] == "1")
    {
        break;
    }

}

  }

  void recipesearch(const vector<string>& ingredientlist) //ifstream& recipes)
 {

ifstream myrecipes;
string line;
string ingredient;
myrecipes.open("recipes.txt");
if (myrecipes.is_open())
{
    for (int i = 0; i < 4; i++)
    {
        ingredient = ingredientlist[i];
        while(getline(myrecipes, line)){
            if (ingredient == line)
            {
                cout << "Hello!" << endl;
            }
            else
            {
                break;
            }
        }
    }   
}
else cout << "Unable to open recipe file!";

myrecipes.close();
}

Here is an example of a recipe used:

Cheese-y Ramen

Prep Time: 5 minutes
Cook Time: 20 minutes
Total Time: 25 minutes
Servings: 2
Ingredients:
8 oz cheddar cheese
1 tablespoon cornstarch
¾ cup milk
2 packages ramen noodles
Directions:
1. Grate cheddar cheese and add with cornstarch into a small bowl
2. Combine with milk in a medium saucepan and cook on medium to low heat until consistent. Keep warm until serving.
3. In a separate pan boil ramen noodles. Set aside the included flavor packets.
4. Once boiling, drain the noodles and combine with cheese.
Recipe from Buzzfeed

This reads the entire recipe file into a string, then looks inside the string for each ingredient. Note: This is extremely brute force. It's fast, but not going to be very accurate. For example, if Cheetos are mentioned in a side bar, not in the recipe itself, they will still be listed.

Credit where it's due, this answer lifts the file read wholesale from Read whole ASCII file into C++ std::string

void recipesearch(const vector<string>& ingredientlist)
{

    ifstream myrecipes;
    string file;
    myrecipes.open("recipes.txt");
    if (myrecipes.is_open())
    {
        // read entire file into string
        myrecipes.seekg(0, std::ios::end);
        file.reserve(myrecipes.tellg());
        myrecipes.seekg(0, std::ios::beg);

        file.assign((std::istreambuf_iterator<char>(myrecipes)),
                    std::istreambuf_iterator<char>());

        // look inside file string for each ingredient
        for (const string & ingredient: ingredientlist)
        {

            if (file.find(ingredient) != file.npos)
            { // found ingredient in file
                cout << ingredient << endl;
            }
        }
    }
    else
        cout << "Unable to open recipe file!";

}

Caveat: A lot of files you'll pull from the web are in encoded in a multi-byte character set to get prettier results and internationalization, not the 7 bit ASCII used by default by most of the standard C++ tools, including the those used in the above example code.

Correctly interpreting which of potentially many multi-byte character sets to use and how to consume them is a discussion topic unto itself, but for the purposes of this assignment OP may be able to get away with ensuring all input files are saved with ASCII encoding.

Try inverting the while and the for loop like such:

...the code before your for loop    
while(getline(myrecipes, line))
{
    for (int i = 0; i < 4; i++)
    {
        ingredient = ingredientlist[i];
        if (ingredient == line)
        {
            cout << "Hello!" << endl;
        }
        else
        {
            break;
        }
    }
}
...the code after your for loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM