Search function using wildcard?

Hi people, I just started C++ yesterday, I'm trying do some basic functions here, but I'm stuck.

Question 1:
I have a infile.txt
1
2
3
4
5
6
Product:Price:Quantity
: is the delimiter
e.g
Chocolate:10:30
Banana:5:15
Candy:2:50


I'm trying to search and delete a line.
Lets say I type Banana, it will delete the line Banana:5:15

It currently works only if I type the full line, Banana:5:15, but if I just type Banana, it will not delete.
Here's my progress so far.
It's a function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void remove_product(string product)
{
	cout << "" << endl;
	ifstream myfile("infile.txt");
	ofstream tempfile("temp.txt");
	string line;	
	cout << "Delete Product: " << endl;
	cin >> product;
	while (getline(myfile,line))
	{
		if (line != product)
		{
			tempfile << line << "\n";
		}
	}
	myfile.close();
	tempfile.close();
	remove("infile.txt");
	rename("temp.txt","infile.txt");

}


Am I doing it wrongly from the start?
Is there a better way to do it?

Question 2:
How do I display a line that I want?

e.g
Chocolate:10:30
Banana:5:15
Candy:2:50

1
2
3
Which line do you want to display: 2

Banana:5:15


I can only display all lines in the file currenly.
Thanks in advance!
Last edited on
1
2
while (getline(myfile,line))
	if (line != product)
You need to write all the line because you are comparing all the line.

2_ What is your code for display? You need to discard all the lines till you find the one you are looking for
for the second question, try using an if statement nested in a for loop. the invariant of the for loop must be the number of rows your on. When the number of rows(invariant) equals your selection... print that line.


h/o I will write some code... I have to look at the libraries to understand those types etc etc
"You need to write all the line because you are comparing all the line."

So how do I delete the line by just entering the Product Name?
Or rather, I output something like:
1 Chocolate:10:30
2. Banana:5:15
3. Candy:2:50
Delete Line No.: 2
Then Banana will be deleted.
This is sort of like Question No.2 's function, but I don't understand how to do it.
My function will be not efficient if I have to type Banana:5:15 just to delete that line...
Last edited on
1
2
3
4
5
6
//Read till the first ':', ignore the rest of the line.
getline(myfile, line, ':');
myfile.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
//Or read the entire line, but extract the interesting part.
getline(myfile, line);
if( product != line.substr(0, line.find(':')) )
ne555, THANKS ALOT!!!

1
2
getline(myfile, line);
if( product != line.substr(0, line.find(':')) )


works like a charm.

Thanks !
Topic archived. No new replies allowed.