2016-12-04 55 views
1

這裏是我的代碼到目前爲止它編譯和運行,但在輸出文件中給出一個大整數,當只詢問斐波納契數爲0.從一個文件中讀取數字,找到每個數字的斐波那契數字並將斐波那契數字寫入一個新文件

我相信找到斐波納契數的循環是正確的,因爲我從另一個程序中複製了循環,我的功能正常。

 #include <stdio.h> 
    #include <ctype.h> 
    #define SIZE 40 

    int main(void) 
{ 
char ch, filename[SIZE]; //variables 

int num; 
int t1 = 0; 
int t2 = 1; 
int index; 
int result; 

FILE *fp; 
printf("Please enter the filename to read: "); //asking for file that is to  be read 
gets(filename); 
// "r" reads the file fopen opens the file 
if ((fp = fopen(filename, "r")) == NULL) 
{ 
    printf("Cannot open the file, %s\n", filename); 
} 
else 
{ 
    puts("Successfully opened, now reading.\n"); //reads through file counting words, upper/lowercase letters, and digits. 

    while ((num=getw(fp)) != EOF) 
    { 

    if(num == 1)  //if the nth term is 1 
    result = 0; 

    else if(num == 2) //if the nth term is 2 
    result = 1; 

    else    //for loop to start at the 3rd term 
    { 
    for(index = 2; index <= num ; index++) 
    { 
    result = t1 + t2; 
    t1 = t2; 
    t2 = result; 
    } 
    } 
    } 
} 



fclose(fp); //closing the file 

char filename2 [SIZE]; 
FILE *fp2; 

fprintf(stdout, "Please enter the file name to write in: "); //asks for file that you want to write to 
gets(filename2); 

if ((fp2 = fopen(filename2, "w")) == NULL) //"w" for writing 
{ 
    printf("Cannot create the file, %s\n", filename2); 
} 
else 
{ 
    fprintf(fp2, "%d", result); 


} 

fclose(fp2); // closing the file 
fprintf(stdout, "You are writing to the file, %s is done.\n", filename2); 

return 0; 

}

+0

與getw一起使用的文本模式文件,這是可疑的。你能提供你的輸入文件的樣本嗎?它是文本/二進制? –

+0

它是一個名爲input.in的文本文件 –

回答

0

可能有其他的問題,但最大的一個是,你正在使用getw,從文件中讀取一個二進制整數(如fread會做),但你從閱讀一個文本文件。

getw()讀取來自流的字(即,一個int)。它提供了與SVr4的兼容性。我們建議您改用fread(3)。

所以你的輸入數據是垃圾,這可能解釋了你得到的大整數。

我將取代:

while ((num=getw(fp)) != EOF) 

通過

while (fscanf(fp,"%d",&num)==1) 

所以數讀作文本。當達到非數字或文件結束時,讀數停止。