如何在C++中传递和返回数组
How to pass and return arrays in C++?
我正在制作一个简单的银行账户处理系统,并将账户信息保存为数组。然而,在传递账户信息时,我遇到了困难。我正在将文本文件中的数组读取到程序中,但这需要从读取文件的函数传递到处理提款的函数,存款和查看余额,传递的数组用于存储当前余额、透支的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::vector
和std::array
,而不是原始数组。
例如,您可以从函数中返回一个std::vector
或std::array
。
此外,请记住
float readFile(float account[8])
相当于
float readFile(float account[])
和
float readFile(float* account)
但是std::vector
和std::array
不会有这个问题。
readFile(account[N]);
这是错误的。您超出了最终值。
readFile(account);
这样更好。
return account[N];
你不能从最终值中返回。取消引用数组中的指针会导致未定义的行为。
相关文章:
- 从 C++ 中的函数返回数组地址问题
- 如何在 c++ 函数中返回数组
- 如何从 c++ 中的函数返回数组
- 为什么 c++ 函数可以正确返回数组的大小?
- 解释通过从函数引用返回数组的语法
- (C++)我的函数不返回数组
- 如何按 C++ 中的值从函数返回数组
- 返回数组中值的指针地址
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 使用数组类返回数组c++
- 如何使函数返回数组?用于制作在VB.NET中使用的DLL
- 从函数 BY VALUE 返回数组,返回结构时会发生什么?
- 调用和打印函数,在 C++ 中返回数组
- 如何使用递归函数返回数组中整数的索引?
- 从函数返回数组时是否需要删除
- 为什么从函数返回数组时需要将数组声明为静态数组.(C++)
- C++返回数组而不进行动态内存分配?
- 在函数 c++ 中返回数组时出现问题
- 如何从C 中的函数返回数组
- 如何使类函数返回数组,然后将其调用并存储在 main 中