detect itemId and delete that line from file
I have a text file name fruit.txt that contains the following information of fruit id, fruitName and fruitQuantity.
Code:
1:pear:30
2:apple:20
3:banana:24
4:orange:15
5:watermelon:35
If let's say I key in 2, it will search for the id=2 and delete the whole line and the id of banana which is orignially 3, will become 2 and orange which is orignally 4 will become 3 etc.
I researched on how it can be done and most suggested to put inside a vector and fout the line.
I know how to put the values in the vector but I have no idea how should I go about searching for the id and if the id is found it will delete that line inside the file. and thus need help.
Code:
ofstream fout;
ifstream readFile("fruit.txt");
while (getline(readFile, line)) {
istringstream iss(line);
iss >> fruitId >> fruitName >> fruitQuantity
fruitConstructor fruitDetails(fruitId,fruitName,fruitQuantity);
fruitVector.push_back(fruitDetails);
}
cout << "Enter fruit id to remove" << endl;
cin >> input;
//duno how I should write to delete the id of the line that
matches my input
for(vector<fruitVector>::iterator it = fruitVector.begin(); it != fruitVector.end(); ++it)
{
}
Re: detect itemId and delete that line from file
Quote:
Originally Posted by
roidbeginner
I researched on how it can be done and most suggested to put inside a vector and fout the line.
Well, it depends on what skills you have to demonstrate with this assignment. In case this all about STL containers, vector would be fine.
However, this can be implemented a pure procedural way alright. No vector required to read file line by line, parse the line, and just skip it to put onto the resultant file once particular id is met.
Quote:
I know how to put the values in the vector but I have no idea how should I go about searching for the id and if the id is found it will delete that line inside the file. and thus need help.
Again, you need to parse every line for its elements, one of them is the id you are to test.
Re: detect itemId and delete that line from file
What is the definiton of fruitConstructor? It would be prefable if you could post all the code rather than just a small snippet. Are the ids in the file always consecutive and start at 1? If so, there's no need to store the ids in the vector and to find a specific id, just index into the vector.