我需要讀取.txt
文件並將第一個數字用作函數getData
中的數組大小。傳遞結構的動態數組C++
在我的代碼中,我能夠讀取文件並將其指定爲數組大小爲listSize
。我也可以用.txt
信息填充陣列的其餘部分。當我打印出getData
函數中的數組時,它可以工作。
問題是,當我嘗試訪問getData
函數之外的數組時,我的程序崩潰了。我對指針和一般的C++都很陌生。我認爲我沒有通過它或正確地調用它。我很難找到信息來幫助我解決問題。
如何訪問我在getData
中創建的陣列?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
struct menuItemType
{
string menuItem;
double menuPrice;
};
void getData(int& listSize, menuItemType menuList[], int orderList[]);
int main()
{
menuItemType *menuList = 0; //-----pointers
int *orderList = 0;
int listSize;
getData(listSize, menuList, orderList);
cout << menuList[0].menuItem; //-----This is what crashes the program
return 0;
}
//-----Get Menu Function
void getData(int& listSize, menuItemType menuList[], int orderList[])
{
//-----Declare inFile
ifstream inFile;
string price, size;
//-----Open inFile
inFile.open("Ch9_Ex5Data.txt");
//-----Get Amount of Items, Convert to int
getline(inFile, size);
listSize = stoi(size);
//-----Set Array Size
menuList = new menuItemType[listSize];
orderList = new int[listSize];
//-----Get Menu
for (int x = 0; x < listSize; x++)
{
//-----Get menuItem
getline(inFile, menuList[x].menuItem);
//-----Get menuPrice convert to double
getline(inFile, price);
menuList[x].menuPrice = stod(price);
}
//------PRINT WORKS HERE ----- This print made me think i created the
//arrays correctly
for (int x = 0; x < listSize; x++)
{
cout << menuList[x].menuItem << endl
<< menuList[x].menuPrice
<< endl;
}
inFile.close();
}
在getData
設置menuList
和orderList
的的.txt
8
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
傳遞指向數組中第一個元素的指針以及一個表示數組大小的整數。 '通過(StructArray * sa,int sizeArray)' –