C++ program that displays on the screen item codes with corresponding
item descriptions and prices. It asks the user to enter the code of the item
purchased by a customer. It looks for a match of the item code stored in items.txt.

How to read a specific line from a text file in c++?

Dani AI

Generated

As pointed out, a linear scan is the simplest solution for a one-off lookup; 's post is a working implementation. For clarity and robustness there are two common, pragmatic options depending on usage patterns:

  1. Occasional lookups — scan line-by-line and stop at the first exact match. Use std::getline to preserve product names that may contain spaces, then parse tokens carefully so price and quantity (often the last two tokens) are extracted reliably.

  2. Frequent lookups — build an in-memory index once (std::unordered_map keyed by the item code) so subsequent queries are O(1). This trades memory for speed and is ideal for a cashier-style lookup loop.

A compact parsing + indexing example (illustrative, minimal error handling):

#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>

struct Item { std::string product, price, qty; };

int main() {
    std::ifstream in("items.txt");
    if (!in.is_open()) return 1;
    std::unordered_map<std::string, Item> index;
    std::string line;
    while (std::getline(in, line)) {
        if (line.empty()) continue;
        size_t a = line.find_first_not_of(" \t");
        size_t b = line.find_first_of(" \t", a);
        size_t z = line.find_last_not_of(" \t");
        size_t y = line.find_last_of(" \t", z);
        size_t x = line.find_last_of(" \t", y - 1);
        if (a==std::string::npos || b==std::string::npos || x==std::string::npos) continue;
        std::string code = line.substr(a, b - a);
        std::string qty  = line.substr(y + 1, z - y);
        std::string price = line.substr(x + 1, y - 1 - x);
        std::string product = line.substr(b + 1, x - b - 1);
        index.emplace(code, Item{product, price, qty});
    }

    auto it = index.find("#4011");
    if (it != index.end())
        std::cout << it->first << " " << it->second.product << " " << it->second.price << "\n";
}

Notes and cautions: treat item codes with leading characters (like '#') as strings, not integers; strip currency symbols (e.g., '$') before numeric conversion; prefer exact string comparison for equality (not substring search) unless pattern matching is intended. For very large files that cannot be loaded, either do a linear scan on each lookup or make a separate index file of byte offsets (store tellg() positions) and use seekg() for fast random access by line number.

Recommended Answers

All 2 Replies

Seems simple.
In psuedo code:

  1. Open file.
  2. Loop
  3. Read a line.
  4. If match, close file, return result.
  5. End of file? Close file, return not found.

Here is a solution that you can use, that will do what you asked.

#include <fstream> 
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <regex>
using namespace std;
int debug = 1;
int z = 0;
int ct = 0;
int match0 = 0;

int chr = 0;
string list[512];
int ver[512];

int input();
int next();
int main()
{
    //Joshua Haglund
    cout << "Item Check" << endl;
    input();
    return 0;
}

int input()
{
    ifstream file;
    file.open("items.txt");
    int endofline = 0;
    string lines = " ";
    string upc = " ";
    string product;
    string price;
    string qty;
    std::cout << "enter item code: ";
    bool status = false;
    bool found = false;

    while (1) {

        z = z + 1;
        upc = " ";
        std::cin >> upc;
        list[z] = upc; 
        ver[z] = status;

        while (file.good()) {


            while (file >> lines >> product >> price >> qty) {

                ver[z] = status;

                std::string s;
                s = lines;
                std::smatch m;
                std::regex e(upc);


                {
                    while (std::regex_search(s, m, e)) {
                        for (auto& x : m) {
                            s = m.suffix().str();
                            std::cout << " ";
                            std::cout << std::endl;
                            std::cout << ""; 
                            found = true;

                        }
                        if (found == true) {
                            std::cout << "" << std::endl;
                            std::cout << "-------------------------------------------------------------------------------" << std::endl;
                            std::cout << setw(15) << "UPC" << std::setw(20) << "Product" << std::setw(17) << "Price" << std::setw(20) << "Qty" << std::endl;
                            std::cout << "-------------------------------------------------------------------------------" << std::endl;
                            std::cout << setw(15) << upc << std::setw(20) << product << std::setw(17) << price << std::setw(20) << qty << std::endl;
                        }
                    }
                }
            }

            std::cout << "" << std::endl;

            //extra credit
            /*
            std::cout << "search history" << std::endl;
            for (ct = 0; ct <= z; ct++) {
                std::cout << list[ct] << " ";
            }
            */
            list[0] = upc;
            ver[0] = status;
            std::cout << "" << std::endl;

            if (found == false)
            {
                std::cout << "no item found." << std::endl;
            }
            file.close();
        }
        next();
    }
    return 0;
}
int next()
{
    std::cout << "" << std::endl;
    input();
    return 0;
}



items.txt
9000012345  Milk-2%         $3.49       20
9000012346  Milk-1%         $3.29       24
7000012347  Bread-White     $2.29       28
7000012348  Bread-Wheat     $2.99       12
#4011       Bananas         $0.49/lbs   14
#94012      Bananas-Organic $0.69/lbs   7



Item Check
enter item code: #4011


-------------------------------------------------------------------------------
            UPC             Product            Price                 Qty
-------------------------------------------------------------------------------
          #4011             Bananas        $0.49/lbs                  14

enter item code: 7000012348


-------------------------------------------------------------------------------
            UPC             Product            Price                 Qty
-------------------------------------------------------------------------------
     7000012348         Bread-Wheat            $2.99                  12
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.