Inventory Management System in C++
Inventory Management System in C++
A college lab stores resistors, capacitors, breadboards and cables across three cupboards. The stock register is a ruled notebook. Someone borrows two boxes of resistors, writes the date in the margin, and within a week the shelf count no longer matches the paper.
Once that register passes a page or two, three questions get expensive. How many boxes remain? Which shelf and block hold them? What is the whole stock worth at current prices? A spreadsheet fixes most of this until two people edit it, or someone needs a fixed-format report for a lab audit.
For our first-year mini project in Computer Programming (BTECES26103), three of us built a console program that answers those three questions from a single text file. It is not a replacement for Tally, Zoho Inventory or ERPNext. Those tools handle barcode scanning, purchase orders, GST, reorder alerts, user roles and audit trails. Our program does one job: keep up to 100 products in memory, let a single user add, update, move, search and delete them, and write every change back to inventory.txt so the data survives a restart. The learning target was classes, inheritance, arrays of objects and file streams, and that target shaped the design more than production requirements did.
Course and Team
We submitted it for Computer Programming (BTECES26103), Semester I of B.Tech CSE at Vishwakarma University, Pune, Division C-C1, under Dr Bharati Sanjay Ainapure. The team was Sarthak, Shreshtha and Ojas. Everything ships as one source file, Inventory_Management_System.cpp, 452 lines of C++17 using only the standard library, plus inventory.txt in the working directory. The full report, presentation and program outputs live in the university submission, not as links here.
1. Four Classes, One Array of Products
The class layout follows the course requirements. User is the base class with a managerName, a default constructor, a parameterized constructor and displayUser(). Record : public User holds one product in 12 private fields with getters for all of them and setters only for quantity, price, shelf, block and the last-updated date. Report owns the table header, two overloaded displayProduct() functions and generateSummaryReport(). Manager : public Record owns Record products[100], a totalProducts counter, a Report member and the string databaseFile = "inventory.txt", and its constructor calls loadDatabase().
The arithmetic lives in two small functions on Record, and storing both a box count and an items-per-box count is what keeps the summary honest:
double getValue() const {
return pricePerItem * quantity * itemsPerBox;
}
int getTotalItems() const {
return quantity * itemsPerBox;
}
quantity counts boxes, not pieces. Four boxes of 12 connectors is 48 items. The program stores price per item, so the stock value needs both multiplications. Without itemsPerBox, the summary would report 4 units and understate the stock by a factor of 12. The field exists to keep that conversion in one place.
Manager : public Record is where the design went wrong. A manager is not a product. That inheritance chain exists so the project can show multilevel inheritance, and it costs us: the manager object carries one unused Record subobject and inherits product setters it should never expose. Composition would model the same code with a Record array and a separate controller, and nothing in main() would change.
2. Eight Menu Options and Five Input Helpers
main() creates one Manager and runs a do-while menu loop. The eight options cover add, update, show all, delete, search, move, report and save-and-exit. Option 8 calls saveDatabase() once more before the loop ends, so the file gets a final rewrite that usually changes nothing. Every successful mutation already saves.
Five helpers absorb the input handling: readInt(prompt, low, high), readDouble(prompt), readText(prompt), readDate(prompt) and readBlock(prompt). Each one keeps asking until the value passes its check. The idea is right. The implementation calls itself again inside a while (true) loop, so a long run of typos grows the call stack. A plain loop with continue does the same job without that risk.
Adding a product checks the ID with findProduct() before the array changes, so P011 cannot be entered twice. Updating is narrow: price or quantity, nothing else. A wrong category or brand means delete and re-enter, which throws away the record's dates and history.
Why Dates and Integers Needed Their Own Validators
A generic "read a number" path is not enough for either type. cin >> int on 4.5 leaves .5 in the buffer for the next read, and a date typed as 31-02-2026 has the right shape and the wrong meaning. readInt takes a low and high bound, so a shelf number of 0 or 101 gets rejected at the prompt instead of reaching a Record. For dates, readDate delegates to isValidDate, which checks a 10-character DD-MM-YYYY layout, confirms that the digit positions hold digits, bounds the month to 1 through 12, bounds the day to at least 1, then looks up the day limit for that month. February gets 29 days only when the year is divisible by 400, or divisible by 4 and not by 100. That single rule rejects 29-02-2025 and accepts 29-02-2024, which a length check and a month check never catch.
bool isValidDate(const string &date) {
if (date.length() != 10 || date[2] != '-' || date[5] != '-') return false;
for (int i : {0, 1, 3, 4, 6, 7, 8, 9})
if (!isdigit(static_cast<unsigned char>(date[i]))) return false;
int day = stoi(date.substr(0, 2));
int month = stoi(date.substr(3, 2));
int year = stoi(date.substr(6, 4));
if (month < 1 || month > 12 || day < 1) return false;
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool leapYear = (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
if (leapYear) daysInMonth[1] = 29;
return day <= daysInMonth[month - 1];
}
The validator proves a date exists. It does not prove the date is today, or that dateLastUpdated comes after dateAdded. A user can type 01-01-2001 for a product added in 2026 and the program accepts it. The digit check also makes the atoi calls safe here, because every character in those three substrings has already been proved numeric. readBlock is simpler: one alphabetic character, uppercased, so shelf blocks stay consistent across records.
3. The Pipe Character That Corrupts Every Later Field
Our file format uses | as the delimiter, so a product name containing a pipe would shift every field after it. readText rejects | along with empty input for that reason. The chain below shows what the check prevents.
Suppose the check were missing and someone typed Cable|1m as a product name. toFileLine() would join the fields and write P012|Cable|1m|Networking|.... That line would carry 13 fields instead of 12. The extra delimiter would push every later value one slot to the right: the category slot would hold 1m, the brand slot would hold the old category, and the shift would run to the end of the line. On the next start, parseRecordLine() would split the line, count 13 fields and reject the row. loadDatabase() would print a warning and skip the product. The add operation would have reported success in the session where it happened.
The timing would make it quiet. The bad line would sit in the file until the program restarts, and the current session would still show the product in memory. Because saveDatabase() rewrites the whole file on every mutation, the malformed line would survive every save. If the field-count check were looser, the parser would accept the 13-field line and store 1m in category without any warning at all. A check at the keyboard is cheaper than a repair pass over the data file.
A file edited outside the program can still contain any text. The only defense there is the field count plus the per-field range checks, and those checks reject a row instead of repairing it. A stricter parser would reject unknown characters before conversion.
4. A Twelve-Field Line and a Hand-Written Parser
The file opens with a header line, then one product per line with 12 pipe-separated fields:
ID|Name|Category|Brand|Quantity|ItemsPerBox|PricePerItem|Shelf|Block|Year|DateAdded|DateLastUpdated
P001|Laptop|Electronics|Dell|10|1|55000.00|10|A|2025|21-11-2026|23-11-2026
loadDatabase() opens the file, skips the header, reads until it has 100 records, and hands each line to parseRecordLine(). The parser walks the string character by character and cuts at each pipe. It rejects anything that does not produce exactly 12 fields, converts the numeric slots with atoi and atof, then range-checks the result: quantity at least 0, items per box at least 1, price at least 0, shelf from 1 to 100, block a single letter, year from 2000 to 2100, and both dates valid. A row that fails any check produces a warning and gets skipped, so one bad line does not kill the load.
atoi and atof are the weak link. atoi("12abc") returns 12, and atof("99.5xyz") returns 99.5. The conversion stops at the first character it cannot use and reports no error. A malformed quantity like 3x becomes 3 and passes the range check, so the corruption survives the load. std::from_chars for the integer fields, or std::stoi and std::stod with a check on how many characters were consumed, would reject the same input. The field count is the obvious check; the conversion behavior is easier to miss until you feed the loader an edited file.
The header also carries no version number. Adding a 13th field later means every existing inventory.txt fails the count check and every row gets skipped on load. A version marker in the header, or a format that tolerates missing trailing fields, would let old files survive a schema change.
5. Delete Shifts Records, Then Rewrites the Whole File
deleteProduct() finds the index, then copies every later record one slot left and decrements totalProducts. The shift has to move records in ascending order. If the loop started from the end, each copy would overwrite the record it still needs, and the array would fill with duplicates of the last product.
Order matters beyond the delete. The array is unsorted, so position is insertion order, and insertion order is what option 3 prints and what option 5 scans. Product ID is the only stable identity. Move a record and its position stays the same. Delete a record in the middle and everything after it shifts by one, which changes the display order but not the data. Forget the decrement and the last product appears twice after a delete, with the summary counting it twice. That is the first thing to check when totals drift.
Every successful add, update, delete and move calls saveDatabase(), which opens the file with ofstream, writes the header and writes every record from index 0 to totalProducts - 1. For 100 records this is fast and easy to reason about. It also means the program has no concurrency story. Two copies open at once will both hold their own arrays, and whichever saves last overwrites the other's changes with no warning. A crash in the middle of a rewrite can leave a truncated file, because the write goes straight to inventory.txt instead of a temporary file that gets renamed after a successful write.
The same rewrite policy makes the 100-record cap visible. addProduct() rejects the 101st product with a message, but nothing suggests archiving old records or growing the array. std::vector<Record> removes the cap and the manual counter, and it would not change a single menu option.
6. A Real Test Run: Eleven Products and a Price Update
We tested the full cycle on the sample inventory: 10 products, from P001 Laptop through P010 Hand Wash. The baseline report showed 345 boxes, 510 items and Rs. 655,350.00 in stock value. We then added P011, a Wi-Fi Router in the Network category from TP-Link, with 10 boxes, 15 items per box, Rs. 2,999.00 per item, shelf 10, block C and year 2026.

The new record was worth Rs. 449,850.00 on its own: 2,999 times 10 boxes times 15 items. The summary moved to 11 products, 355 boxes, 660 items and Rs. 1,105,200.00. We updated its price, moved it to another shelf and block, and deleted it. The report returned to 345 boxes, 510 items and Rs. 655,350.00, which matched our hand calculations. That round trip is the test we trust most, because it exercises add, update, move, delete, save and load in one pass.
The move in that run did not test a collision, and option 6 has no check for one. moveProduct() changes the shelf, block and last-updated date without asking whether another product already sits on the target shelf. In a real lab that is a collision: two records claim the same slot, and the person picking stock cannot tell which one is stale. A capacity field or a check across existing records would catch it, and our program creates the conflict instead.
7. What We Got Wrong
The honest list is long, and most of it comes from treating a learning exercise as a design.
The missing features follow the same pattern. Search is narrow: it matches Product ID only, so a user who remembers "Wi-Fi Router" but not "P011" has to scroll the full list. There is no login, so anyone at the keyboard can delete a record. No roles, no audit log, no low-stock alert, no backup step and no category-wise report. A real deployment needs all of them, and none belong in a first-semester file.
If we rebuilt it, the order would be std::vector first, stricter number parsing second, a composition-based Manager third, and SQLite after that. SQLite gives transactions, concurrent reads and a real query language without much more code than our text parser. Stock thresholds would come next, because "quantity below 5 boxes" is the alert a lab actually needs. An audit trail of who changed what, and an import or export path for a spreadsheet, would make the tool usable by someone who did not write it.
Quick Takeaways
- A delimiter allowed inside free text will corrupt the file at the next load. Validate it where the user types, not in the parser that reads the mess back.
- Inheritance should model an is-a relationship. Our
Manager : public Recordchain demonstrated multilevel inheritance and produced a controller with product setters. - Whole-file rewrite is acceptable at 100 records only if one process writes at a time. Write to a temp file and rename before trusting it with real data.
- Test the add, update, move and delete cycle until the summary returns to its starting totals. It is the fastest way to catch a missing counter decrement or a stale total.