Given a .txt file containing this data (it can contain any number of similar lines):
hammer#9.95
shovel#12.35
Using a flag controlled while loop in C++, when an item name is searched for in the imported .txt file, the price of the item (separated by the hash) should be returned.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
inFile.open(invoice1.txt);
char name;
char search;
int price;
ifstream inFile;
ofstream outFile;
bool found = false;
if (!inFile)
{
cout<<"File not found"<<endl;
}
outFile.open(invoice1.txt)
inFile>>name;
inFile>>price;
cout<<"Enter the name of an item to find its price: "<<endl;
cin>>search;
while (!found)
{
if (found)
found = true;
}
cout<<"The item "<<search<<" costs "<<price<<"."<<endl;
return 0;
}
The following variables can only hold a single character.
char name;
char search;
A fix would be to replace them with for examplechar name[30];
this variable can hold 30 characters.
But it's best to use std::string
as it can grow dynamically to any size.
std::string name;
std::string search;
You also open the same file twice, once with read permissions, and once with write permissions. In your case, you only need to read it. If you needed write/read access, you can do that using the stream flags std::fstream s("filename.txt",std::ios::in | std::ios::out);
Here's a full example of what you are trying to accomplish:
std::cout << "Enter the name of an item to find its price: " << std::endl;
std::string search;
std::cin >> search;
std::ifstream inFile("invoice1.txt");
if (inFile) // Make sure no error ocurred
{
std::string line;
std::string price;
while (getline(inFile, line)) // Loop trought all lines in the file
{
std::size_t f = line.find('#');
if (f == std::string::npos) // If we can't find a '#', ignore line.
continue;
std::string item_name = line.substr(0, f);
if (item_name == search) //note: == is a case sensitive comparison.
{
price = line.substr(f + 1); // + 1 to dodge '#' character
break; // Break loop, since we found the item. No need to process more lines.
}
}
if (price.empty())
std::cout << "Item: " << search << " does not exist." << std::endl;
else
{
std::cout << "Item: " << search << " found." << std::endl;
std::cout << "Price: " << price << std::endl;
}
inFile.close(); // close file
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments