Search Inside text files

Hello, I will ask this in advance so that I will save more time. So,I'm building a program that will ask the user to enter a product ID and the program will output it's name and price. The question is should I perform the linear search(?)
in the ifstreamsource file or should I do it in another source file?
I will keep this thread updated. Thanks in advance.

Ok, Now I'm stuck how do I get the correct product name and price loaded when the user enters it's ID?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <fstream>

using namespace std;

int Search(int Searcharray[], int sizeofArray, int searchValue);

int main ()
{
    int i=0;
    int productID;
    char productName[100];
    double Price[20];
    
    ifstream infile("Productfile.txt");
    if (infile.is_open())
    {
        while (!infile.eof())
        {
            infile >> productName[i] >> Price[i];
            i++;//im stuck here
        }
        
    }
    else
    {
        cout << "File not open" << endl;
    }
}

int Search(int Searcharray[], int sizeofArray, int searchValue);
{
    for (int i=0; i < sizeofArray; i++)
    {
        if (searchValue == Searcharray[i])
        {
            return i;
        }
    }
    return -1;
}


Here's the content of the text file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
4356 // ID
Olive Oil // Product Name
4.56 //Price
5478
Corn Oil
5.67
7865
Fish Oil
6.56
3245
Chicken Oil
9.76
1345
Vegetable Oil
8.98
7865
Canola Oil
10.56
Last edited on
Maybe use a struct to hold each product. Then create an array of these objects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <fstream>
#include <string>

    using namespace std;

struct product {
    int ID;
    string name;
    double price;
};

int Search(product Searcharray[], int sizeofArray, int searchValue);

int main()
{
    char filename[] = "Productfile.txt";
    ifstream infile(filename);

    if (!infile.is_open())
    {
        cout << "Unable to open file: " << filename << endl;
        return 1;
    }

    product prods[100];
    int count = 0;

    while ((infile >> prods[count].ID >> ws) 
            && getline(infile, prods[count].name) 
            && infile >> prods[count].price)
        count++;

    cout << "Number of products read from file: " << count << endl;

    return 0;
}

int Search(product Searcharray[], int sizeofArray, int searchValue)
{
    for (int i=0; i < sizeofArray; i++)
        if (searchValue == Searcharray[i].ID)
            return i;
            
    return -1;
}
Topic archived. No new replies allowed.