[英]Cout 2D Array to console C++
我在讓 2D 數組正確顯示到控制台時遇到問題。 目前,它顯示為
Ally Baba's Burgers
-------------------
B Burger 3
S
Soda 1
F Fries
2
C Chips 1.5
-------------------
X - Clear Sale
T - Total
E - End Shift
Enter command:
我希望它顯示為
Ally Baba's Burgers
-------------------
B Burger 3
S Soda 1
F Fries 2
C Chips 1.5
-------------------
X - Clear Sale
T - Total
E - End Shift
Enter command:
我從中獲取菜單選項的文本文件看起來與上面完全相同,但減去了我要插入的 cout。
void getMenu(string menu[][3]){
string line;
ifstream file("Menu.txt");
if (!file){
cout << "File failed to opened\n";
}
for (int i = 0; i < 4; ++i){
for (int j = 0; j <3; ++j){
if (getline(file, line, ' ')){
menu[i][j] = line;
}
}
}
file.close();
}
void displayMenu(string menu[][3], char & choice){
cin.clear();
cout << "Ally Baba's Burgers\n";
cout << "-------------------" << endl;
for (int i = 0; i < 4; ++i){
for (int j = 0; j < 3; ++j){
cout << menu[i][j] << ' ';
}
cout << endl;
}
cout << "-------------------" << endl;
cout << "X - Clear Sale" << endl;
cout << "T - Total" << endl;
cout << "E - End Shift\n" << endl;
cout << "Enter command: ";
cin >> choice;
}
感謝您的幫助。
正如@BessieTheCow 指出的那樣, getline 正在讀取直到找到下一個空間。 不使用它或指定新的行分隔符。
假設您的 Menu.txt 文件以換行符結束每一行,請執行以下操作:
void getMenu(string menu[][3]){
string line;
ifstream file("Menu.txt");
if (!file){
cout << "File failed to opened\n";
}
for (int i = 0; i < 4; ++i){
for (int j = 0; j <3; ++j){
if (getline(file, line)){
menu[i][j] = line;
}
}
}
file.close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.