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

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 can I output only a specific line from a text file after the user inputs the item code?

c++


Solution 1:[1]

You need to read the file line-by-line (std::getline), extract (depending on the exact format, e.g. by searching for a whitespace in the string) and compare the code and then return the corresponding line on a match.

It is not possible to access lines from a text file directly by index or content.

This is assuming that you mean the file contains lines in the form

code1 item1
code2 item2
//...

If the code is just the index of the line, then you only need to call std::getline in a loop with a loop counter for the current index of the line.


If you do this multiple times on the same file, you should probably parse the whole content first line-by-line into a std::vector<std::string> or a std::(unordered_)map<std::string, std::string> or something similar to avoid the costly repeated iteration.

Depending on the use case, maybe it would be even better to parse the data into a database first and then query the database, even if it is only e.g. sqlite or something like that.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1