2013-12-10 71 views
-1

下面的代碼給我:爲什麼下面的代碼給了我不同的預期輸出?

3276560 January 
3276560 February 
3276560 March 
3276560 April 
3276560 May 
3276560 June 
3276560 July 
3276560 August 
3276560 September 
3276560 October 
3276560 November 
3276560 December 

但我預計

1 January 
2 February 
3 March 
4 April 
5 May 
6 June 
7 July 
8 August 
9 September 
10 October 
11 November 
12 December 

哪裏是我的錯?

#include <stdio.h> 

int main(void){ 

int i; 
char a[10], b[10]; 
char *ptrMonths[] ={"January","February","Mach","April","May","June", "July","August","September","October","November","December"}; 
FILE *ptrToMonthFile; 
ptrToMonthFile=fopen("Monthsrr.txt", "w"); 

for (i = 0; i < 12; i++) 
{ 
    fprintf(ptrToMonthFile, "%d %s\n", i+1, ptrMonths[i]); 
} 

fclose(ptrToMonthFile); 

ptrToMonthFile=fopen("Monthsrr.txt", "r"); 

for (i = 0; i < 12; i++) 
{  
    fscanf(ptrToMonthFile,"%d %s\n", a, b); 
    fprintf(stdout, "%d %s\n", a, b); 
} 

fclose(ptrToMonthFile); 

getch(); 
} 
+0

a不是int。你的意思是在你最後的fprintf寫我嗎? – PakkuDon

+0

是的,我想顯示我,但我把它存儲在一個字符數組。我怎樣才能把它顯示爲整數? – Lyrk

+1

在fscanf中使用&var讀取一個整型變量。如果你想把它看作是%s,而不是%d – LoztInSpace

回答

0
for (i = 0; i < 12; i++) 
{  
    fscanf(ptrToMonthFile,"%s %s\n", a, b); 
    fprintf(stdout, "%s %s\n", a, b); 
} 

我改變科特迪瓦%s到%s的現在的工作。

+1

你的方法確實有效,但是你可以通過使用'int'來存儲月份而不是字符串來保存一些空間。 – Mike

+0

是的,這樣做更好。我會像那樣改變。謝謝 – Lyrk

0
fprintf(stdout, "%d %s\n", i+1, ptrMonths[i]); 
0

如果你想用%d來讀取它,那麼a應該是int。如果你想將它作爲字符串讀取,請改用%s。

2

幾個問題:

類型爲a需求是一個int,因爲你%d讀它。

int a; 
char b[10]; 

您需要的地址傳遞給fscanf

fscanf(ptrToMonthFile,"%d %s\n", &a, b); 

另外:你也應該檢查所有文件函數的返回值。任何I/O都可能失敗。

相關問題