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!