给定包含此数据的.txt文件(它可以包含任意数量的类似行):
hammer#9.95
shovel#12.35
在C ++中使用while循环控制的标志,当在导入的.txt文件中搜索项目名称时,应返回项目的价格(由散列分隔)。
#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;
}
答案 0 :(得分:0)
以下变量只能包含一个字符。
char name;
char search;
修复方法是替换它们,例如char name[30];
此变量可以容纳30个字符。
但最好使用std::string
,因为它可以动态增长到任何大小。
std::string name;
std::string search;
您还可以打开同一个文件两次,一次具有读取权限,一次具有写入权限。在您的情况下,您只需要阅读它。如果您需要写入/读取访问权限,则可以使用流标记std::fstream s("filename.txt",std::ios::in | std::ios::out);
以下是您要完成的完整示例:
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
}