我是这个网站的新手,本学期使用 C++ 语言进行编程。
真的试了2天,问过同学也不知道。一位同学说要使用二维数组,但我不知道那是什么,我的教授也没有讲过二维数组。
我被困住了,非常感谢帮助。
输入文件包含以下内容:
Plain_Egg 1.45
Bacon_and_Egg 2.45
Muffin 0.99
French_Toast 1.99
Fruit_Basket 2.49
Cereal 0.69
Coffee 0.50
Tea 0.75
idk如何显示所有“用户”订单
基本上是一张收据,比如他点了这个和多少,然后问“你还想要什么吗?”,然后再记下订单号和数量,然后最后还回一张看起来像这样的收据
bacon_and_eggs $2.45
Muffin $0.99
Coffee $0.50
Tax $0.20
Amount Due $4.14
这是我的代码:
// Libraries
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <cmath>
using namespace std;
//structures
struct menuItemType {
string itemName;
double itemCost;
};
// Prototypes
void header();
void readData(menuItemType menu[]);
void Display(menuItemType menu[]);
int main() {
header();
menuItemType menu [8];
readData(menu);
Display(menu);
//system("pause");
return 0;
}
void header() {
char c= 61;
for (int i=0; i < 64; i++) {
cout << c;
}
cout << c << endl;
cout << endl;
cout << "Breakfast Menu" <<endl;
for (int i=0; i < 64; i++) {
cout << c;
}
cout << "" << c << endl;
cout << endl;
}
void readData(menuItemType item[]) {
int i=0;
ifstream in;
in.open("input.txt");
cout << fixed << setprecision(2);
while(!in.eof()) {
in >> item[i].itemName >> item[i].itemCost;
++i;
}
}
void Display(menuItemType item[]) {
int choice = 0, quantity = 0;
double total = 0.0, totalF = 0.0, tax = 0.0;
char exit = 'y';
int j = 1, z = 1, i = 1;
//the Menu
for (int i=0; i<8; i++){
cout << j << ". " << setw(18) << left << item[i].itemName << "$" << setw(10) << item[i].itemCost << endl;
j++;
}
cout << endl;
while(exit == 'y' || exit == 'Y') {
cout << "Please Enter your Selection or 0 to Exit : ";
cin >> choice;
if(cin.fail()) {
cout << "*******Invalid selection*******" << endl;
cin.clear();
cin.ignore(1000,'\n');
} else if (choice==0) {break; }
else {
cout<< "Enter Quantity: ";
cin>> quantity;
if (quantity==0) { break;}
else {
choice--;
total += (quantity * item[choice].itemCost);
tax = (total * .05);
totalF = total + tax;
cout << endl;
}
cout << endl;
cout << "======================================================" << endl;
cout << item[choice].itemName << "\t\t" << item[choice].itemCost << endl;
cout << "======================================================" << endl;
cout << "Do you want to continue (Y/N): ";
cin >> exit;
}
}
}
最佳答案
首先,您不需要为此需要二维数组!据我所知,您已经有了一个合适结构的一维数组:存储对象名称及其价格的东西。有点缺少的是数组中当前有多少对象以及它有多少空间。如果您想使用整个数组的内容,请确保您的对象已正确初始化,例如,名称为空(这实际上是自动发生的)并且价格为零(这不是)。
我不确定这是否是复制和粘贴错误,但 header 包含不正确。 include 指令应该看起来像这样:
#include <iostream>
读取值的实际循环并没有真正起作用:您始终需要在尝试读取之后检查输入是否成功!此外,使用 eof()
用于检查循环结束是否错误(我不知道人们是从哪里学来的;任何推荐使用 eof()
来检查输入循环的书只对刻录有用)。循环应该看起来像这样:
while (i < ArraySize && in >> item[i].itemName >> item[i].itemCost)
++i;
}
这也修复了在输入多于数组可以消耗的情况下潜在的边界溢出问题。您可能需要考虑使用 std::vector<Item>
相反:此类会跟踪有多少元素,您可以根据需要添加新元素。
请注意,您并没有说出您遇到的问题:您需要更清楚地描述您的实际问题是什么。以上只是更正了现有的错误,重新调整了观察的方向(即暂时忘掉二维数组)。
关于c++ - 如何使用 Visual Studio 在 C++ 中使用二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13336927/