[英]Take multiple separate inputs from lines read in from file in C
基本上我有一些问题。
我要解决的问题涉及一个“银行程序”,该程序从文本文件获取其信息。 它读取代码的前五行(均为浮点数),并将每行用作起始余额。
接下来,下面的1-5行代码均以一个字符开头,表示该代码所影响的帐户。 接下来是单个字母,指示提款或存款等。其后是该操作将使用的金额。 我必须使用多种功能。
到目前为止,这就是我所知道的,我知道在进行伪代码处理时,在伪代码中还留有一些空格。
float balance();
float withdraw();
float deposit();
float update();
#define INTEREST 3.5;
int main(){
//initializing variables
int count =0,count2=0,acctNum=1,acct1,acct2,acct3,acct4,acct5,i=0;
float orgBalance, balance;
char activity,B,W,U,D;
//opening files
FILE *input;
input = fopen("bankfile.txt","r");
//error checking that file opened correctly
if (input == NULL){
fprintf(stderr, "Can't open input file!\n");
exit(1);
}
printf("Account Balance\n");
printf("------------------------\n");
while(count<5){
fscanf(input,"%f",&orgBalance);
//printf("%d %.2f\n",acctNum,orgBalance);
//acctNum++;
i++;
count++;
printf("%d balance is %.2f\n",i,orgBalance);
}
printf("------------------------\n");
while(fscanf(input, "%d ",&i)!=EOF){
//while(count2<5)
fgetc(i);
switch (activity){
case 'B':
balance;
;
break;
case 'W':
withdraw;
;
break;
case 'D':
deposit;
;
break;
case'U':
update;
;
break;
}
count2++;
}
system("pause");
return 0;
}
float balance(){
float bal;
return bal;
}
float withdraw(){
float bal1, bal2;
if(bal1>bal2){
return bal1 - bal2;
}
else{
printf("Sorry, you can't withdraw that much");
return bal1;
}
}
float deposit(){
float bal1,bal2;
return bal1 += bal2;
}
float update(){
float bal;
return bal*= INTEREST;
}
这些是错误的
switch (activity){
case 'B':
balance;
;
....
你的意思是
switch (activity){
case 'B':
balance(); <<<======
;
您可以使用数组提取类似的帐户:
float ogAcnts[5] = {0,0,0,0,0}; // original account balances initialized to zero
fscanf(input, "%f%f%f%f%f", &ogAcnts[0], &ogAcnts[1], &ogAcnts[2], &ogAcnts[3], &ogAcnts[4]);
如果需要保留原始余额以供将来参考,则可以使用第二组数组来存储新余额:
float newAcnts[5] = {0,0,0,0,0}; // initialized to zero, could also be replaced with the original balances
要显示原始帐户余额:
// you can fill in the rest
for(int i=0; i<=4; i++)
{
printf("%d balance is %.2f\n",i,ogAcnts[i]);
}
您可以在扫描时跳过文件中的帐户余额,如下所示:
fscanf(input+5, %d%c%f, &acountNum, &transactionType, &amount); // note these variables don't exist in your code but it's an example of how you could use them
然后,您可以按照相同的方法来获取剩余的交易记录。 获取交易参数并对其执行操作。 使用数组访问余额而不是文件。 第一个帐户将是元素0,并以索引号4(从零开始)结束的帐户号5结束。 因此,您将必须遵循这种模式。 我之所以这样说,是因为交易是如何用帐号标记的(以0或1开头)。 如果您使用基于零的值,则可以更轻松地访问数组中的帐户余额。 像此示例一样,如果帐户#2中包含400,并且您从第一个帐户开始,即帐户0,开始,则您可以将帐户号和金额传递给交易功能,例如“ 2 W 200”:
...
newAcnts[accountNum] = ogAcnts[accountNum]-amount; // withdraw example using the variables from above
注意:最好每个帐户只有一个结余,除非您(如前所述)在开始之前需要知道结余是多少。 因为对于同一帐户上的任何其他交易,您都希望使用newAcnts [accountNum]来拥有正确的帐户余额。 或者,在开始任何交易之前,将原始余额复制到新帐户阵列中,然后仅在newAcnts阵列上进行交易。 希望这是有道理的:)
newAcnts[accountNum] = newAcnts[accountNum]-amount; // withdraw example
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.