[英]2D array printing
因此,我正在創建一個程序,該程序讀取一個名為“ Bankfile.txt”的文件,第一個數字“ 3”表示我們正在使用多少個帳戶。 數字“ 123”,“ 467”和“ 499”是銀行帳號,每個數字旁邊的數字是其原始余額。 在我的代碼我使用的是二維數組在掃描他們。我想,我所擁有的一切,在掃描這些正確的,但是當我運行該程序正在打印的賬戶號碼很奇怪的看到這里 。 關於為什么要這樣打印的任何想法?
謝謝!
#include <stdio.h>
int main(){
FILE* file;
file = fopen("bankfile.txt","r");
int accounts,b=1,w=2,d=3,u=4,i,j,accNum,origBal;
float interest = .0185;
float test;
float accountInfo[accNum][origBal];
fscanf(file, "%d", &accounts);
for(i = 0; i < accounts; i++)
{
fscanf(file, "%d", &accountInfo[i]);
for(j = 0; j < 1; j++)
{
fscanf(file, "%f", &accountInfo[i][j]);
printf("Account %d has a balance of $%.2f\n", accountInfo[i], accountInfo[i][j]);
}
}
system("pause");
return 0;
}
好的,這里不是 二維數組 ,這在概念上是錯誤的。 一個帳號只有一個余額與之關聯。 因此,您只有一個維,但是數據有多個字段...在C中使用struct
。這是一些示例代碼,可以產生您期望的輸出:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* data structure holding a bank account */
typedef struct account
{
int id;
double balance;
} account;
int main(void)
{
int cap = 1024; /* initial capacity of account array */
int count = 0; /* number of accounts */
char buf[1024]; /* buffer for a line of text */
char *tok; /* token from text line */
FILE *bankfile;
int i;
account *accounts = malloc(cap * sizeof(account));
bankfile = fopen("bankfile.txt", "r");
while (fgets(buf, 1024, bankfile))
{
int accId;
tok = strtok(buf, " \t\r\n");
if (!tok) continue;
accId = atoi(tok);
if (accId > 0)
{
/* first token in line was a positive integer */
tok = strtok(0, " \t\r\n");
if (tok)
{
/* there was a second token in the same line, then we found
* an account with a balance */
accounts[count].id = accId;
accounts[count].balance = atof(tok);
if (++count == cap)
{
cap *= 2;
accounts = realloc(accounts, cap * sizeof(account));
}
}
}
}
fclose(bankfile);
for (i = 0; i < count; ++i)
{
printf("Account %d has a balance of $%.2f\n",
accounts[i].id, accounts[i].balance);
}
free(accounts);
return 0;
}
可以通過先讀取第一行然后僅分配所需數量的account
元素來簡化此操作。
當然,對於生產而言 ,向fopen()
和malloc()
以及朋友添加錯誤檢查...
首先,我認為您不了解二維數組的概念。 當您有一個2D數組( foo
)並向其中添加兩個數組時,它將看起來像這樣。
int foo[][] = { {1,2,3} {4,5,6} };
當您調用foo[0]
它實際上將引用添加的第一個數組(即[1,2,3]
),而foo[1]
將引用第二個數組。 您應該改用兩個單獨的數組,分別稱為accountNum
和accountBal
。
最后,您永遠不會將值賦予accNum
或origBal
,這會使您的2D數組成為空數組。 因此,您可以改為根據accounts
變量為它們動態分配內存。
請記住,您應該更改主要邏輯以解決這些問題。
fscanf(file, "%d", &accounts);
accountNum = malloc(sizeof(int) * accounts);
accountBal = malloc(sizeof(float) * accounts);
for(i = 0; i < accounts; i++) {
fscanf(file, "%d", &accountNum[i]);
fscanf(file, "%f", &accountBal[i]);
printf("Account %d has a balance of $%.2f\n", accountNum[i], accountBal[i]);
}
free(accountBal);
free(accountNum);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.