所以基本上我的程序分为3个文件:header,implementation,main 标题:
#ifndef CUSTOMER_H
#define CUSTOMER_H
#include <string>
using std::string;
#include <fstream>
using std::ofstream; // Output file class
using std::ifstream; // Input file class
class MenuList {
private:
int _itemNo;
string _category;
string _descript;
double _price;
public:
MenuList();
void readin(ifstream& infile); // Read customer from file
void display();
void order();
};
#endif
实施:
#include "prog2Head.h"
#include <iostream>
using std::cout;
using std::cin;
// Default constructor
MenuList::MenuList() : _itemNo(0), _category(""), _descript(""), _price(0.0) { }
// Read customer details in from file
void MenuList::readin(ifstream& infile) {
infile >> _itemNo;
getline(infile, _category, ':');
getline(infile, _descript, ':');
infile >> _price;
}
// Display customer details
void MenuList::display() {
cout << _itemNo << ' ' << _category << " - " << _descript <<"\t\t";
}
void MenuList::order() {
char cont;
int qty;
cout << "Order:\n";
cout << "__________\n";
do{
cout << "Item: ";
cin >> _itemNo;
cout << "Quantity: ";
cin >> qty;
cout << "Continue?(y)";
cin >> cont;
} while(cont == 'y');
}
和主要:
#include "prog2Head.h"
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
#include <fstream>
using std::ofstream; // Output file class
using std::ifstream; // Input file class
int main() {
ifstream fromDisk("menu.txt"); // Open file for reading
while(!fromDisk.eof()) { // Loop until end of file is reached
MenuList menu; // Create customer object
menu.readin(fromDisk); // Read customer from file
if(!fromDisk.eof()) { // Display customer
menu.display();
}
}
MenuList menu;
menu.order();
return 0;
}
文件如:
1鱼盘:炸鱼薯条:21
2肉菜:牛排和dk:15.3
3肉菜:羊肉和鸡肉:21.9
最后一个数字是价格,第一个是ID。 我想输入ID并显示具有该ID的项目的价格。我知道这与创建数组有关,但我一直在寻找一段时间,但仍然无法使它工作。