【发布时间】:2018-05-10 11:55:19
【问题描述】:
我的文本文件:
1:Meat Dish:Steak:11.5
2:Fish Dish:Fish and chips:12
所以基本上我正在尝试读取一个文件,通过选择 1 或 2 选择一道菜,然后将名称和价格写入文件。
这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <vector> // We will use this to store Players
using std::string;
using std::ofstream;
using std::ifstream;
using std::cout;
using std::cin;
using std::vector;
struct MenuList { // Define a "Menuu" data structure
string itemNo;
string category;
string descript;
double price;
};
std::istream& operator>>(std::istream& infile, MenuList& menu) {
getline(infile, menu.itemNo, ':');
getline(infile, menu.category, ':');
getline(infile, menu.descript, ':');
infile >> menu.price;
// When we have extracted all of our information, return the stream
return infile;
}
std::ostream& operator<<(std::ostream& os, MenuList& menu) {
os << "" << menu.itemNo << " " << menu.category << " - " <<
menu.descript;
// When we have extracted all of our information, return the stream
return os;
}
void Load(vector<MenuList>& r, string filename) {
std::ifstream ifs(filename.c_str()); // Open the file name
if(ifs) {
while(ifs.good()) { // While contents are left to be extracted
MenuList temp;
ifs >> temp; // Extract record into a temp object
r.push_back(temp); // Copy it to the record database
}
cout << "Read " << r.size() << " records.\n\n";
}
else {
cout << "Could not open file.\n\n";
}
}
void Read(vector<MenuList>& r) {// Read record contents
for(unsigned int i = 0; i < r.size(); i++)
cout << r[i] << "\n";
}
void Search(vector<MenuList>& r) {// Search records for itemNo
string n;
int a;
char cont;
cout << "Order\n_______\n";
do {
cout << "Enter quantity: ";
cin >> a;
cout << "Enter dish: ";
cin >> n;
for(int i = 0; i < r.size(); i++) {
if(r[i].itemNo.find(n) != string::npos)
cout << r[i].category << " - " <<r[i].descript << ' ' <<
a*r[i].price;
std::ofstream ofs;
ofs.open ("transactions.txt", std::ofstream::out | std::ofstream::app);
ofs << r[i].category << " - " <<r[i].descript << ' ' << a*r[i].price << "\n";
}
cout << "\n\nContinue to add to order?(y)";
cin >> cont;
}while(cont == 'y');
}
int main() {
vector<MenuList> records;
Load(records, "delete.txt");
Read(records);
Search(records);
return 0;
}
当我输入要在屏幕上显示的菜并写入文件时,在屏幕上显示菜可以正常工作,但是当它将菜写入文件时,即使我只选择了 1,它也会同时写入它们。
如果我选择第一道菜,预期输出到文件中:Meat Dish - Steak 11.5
但我得到的是:1:Meat Dish:Steak:11.52:Fish Dish:Fish and chips:12
问题出在附近:
do {
cout << "Enter quantity: ";
cin >> a;
cout << "Enter dish: ";
cin >> n;
for(int i = 0; i < r.size(); i++) {
if(r[i].itemNo.find(n) != string::npos)
cout << r[i].category << " - " <<r[i].descript << ' ' <<
a*r[i].price;
std::ofstream ofs;
ofs.open ("transactions.txt", std::ofstream::out | std::ofstream::app);
ofs << r[i].category << " - " <<r[i].descript << ' ' << a*r[i].price << "\n";
}
cout << "\n\nContinue to add to order?(y)";
cin >> cont;
}while(cont == 'y');
此时的任何事情都对我有帮助。提前谢谢你。
【问题讨论】: