My question is concerning how I can get the portion where I'm input streaming from the txt file to properly loop through the text file and compare the integers and then get the next line the txt file looks something like this. I'm supposed to create this as a function and use the return values in another code. However, I can't figure out to loop through the txt file properly as my code currently returns the product code once properly in the format needed but then returns the else statement every time after.
323
notebook
987
sweater
123
water bottle
#include <iostream>
#include <fstream>
#include <string>
#include "inventory.hpp"
using namespace std;
string locateProduct (int num)
{
int line;
string productName;
ifstream myfile;
myfile.open("inventory.dat");
if(!myfile)
cout << "file failed to open";
while(myfile >> line)
{
if(line == num)
{
cin.ignore();
getline(myfile,productName);
cout << "Product code " << num << ": " << productName << endl;
myfile.close();
return productName;
}
else
{
cout << "Code not found, try again." << endl;
myfile.close();
return "NOTFOUND";
}
}
}
This where I'm calling the function in another file:
int productcode;
do
{
cout << "Enter product code (-1 to end): ";
cin >> productcode;
cout << endl;
if (productcode != -1)
{
locateProduct(productcode);
}
} while(productcode != -1);
output =
Enter product code (-1 to end): 209
Code not found, try again.
Enter product code (-1 to end): 323
Product code 323:
Enter product code (-1 to end):
However, 209 is a valid number and 323 should print out notebook.