如何在C++中传递和返回数组

How to pass and return arrays in C++?

本文关键字:返回 数组 C++      更新时间:2023-10-16

我正在制作一个简单的银行账户处理系统,并将账户信息保存为数组。然而,在传递账户信息时,我遇到了困难。我正在将文本文件中的数组读取到程序中,但这需要从读取文件的函数传递到处理提款的函数,存款和查看余额,传递的数组用于存储当前余额、透支的bool的替身以及最后3次提款和存款。

提取功能看起来像

float Withdraw()                                        //function handled withdraw requests
{
//variables
const int M = 3;                                //declare const int for withdraws
const int N = 8;                                //declare const int for account
float withdrawAmount = 0.0f;                    //used for internam laths in function   
float currentBalance = 0.0f;                    //used internally in function
float newBalance = 0.0f;                        //passed to write function
float withdraws[M];                             //passed to write function
float account[N];                               //passed and returned from read function
//call readFile function
readFile(account[N]);
cout << account[0];
//user interface
cout << "Withdraw opnened" << endl;                 //prompts user for input of a withdraw amount and displays current balance
cout << "Your Current Balance is: " << currentBalance << endl;
cout << "How Much Would You Like to Withdraw?" << endl;
cin >> withdrawAmount;
newBalance = currentBalance - withdrawAmount;           //calculates balance after withdraw
withdraws[2] = withdraws[1];
withdraws[1] = withdraws[0];
withdraws[0] = withdrawAmount;
system("PAUSE");
system("cls");
writeFile(newBalance, withdraws[M]);
Menu();
return 0;
}

读取文件的功能看起来像

float readFile(float account[8])
{
//variables
const int N = 8;
float accountRead[N];
//read file
ifstream file("floats.txt");
if (!file.is_open())
{
    cerr << "Error opening file" << endl;
    return 0;
}
for (int i = 0; i < N && file >> accountRead[i]; ++i)
    ;
if (file)
{
}
account = accountRead;
return account[N];
}

任何指导都将不胜感激,因为我花了几个小时试图研究这一点,但一无所获

使用double,而不是float。例如,文字3.14是类型double。这是因为double是C++中默认的浮点类型,当没有真正重要的理由时,您会理所当然地使用这种浮点类型。

使用std::vectorstd::array,而不是原始数组。

例如,您可以从函数中返回一个std::vectorstd::array

此外,请记住

float readFile(float account[8])

相当于

float readFile(float account[])

float readFile(float* account)

但是std::vectorstd::array不会有这个问题。

readFile(account[N]);

这是错误的。您超出了最终值。

readFile(account);

这样更好。

return account[N];

你不能从最终值中返回。取消引用数组中的指针会导致未定义的行为。