這是您的問題的解決方案,嘗試閱讀和理解代碼。基本上,這個想法是正確的,但我糾正了你犯錯誤的地方。解決方案的主要工作是在while()
循環中。所以通過它。
#include<stdio.h>
//#pragma warning(disable : 4996)
int main()
{
int i=0, in = 0;
int j=0, jn = 0;
int numberOfCol = 0;
double num1,num2;
double point[65][2];
FILE *myfile=NULL;
myfile = fopen("test.txt", "r");
if (myfile == NULL)
{
printf("can not open file\n");
}
else
{
while (!feof(myfile))
{
fscanf(myfile, "%lf %lf", &num1, &num2);//since your file contains two numbers per row you need two variables to store the values
point[i][j] = num1;//At this point (i=0,j=0) you will get the first value of in the row/line.
printf("%lf ", point[i][j]);
++j;//incremet j so that you move the index to next column i.e (i=0,j=1)
point[i][j] = num2;//store the second column value of the row/line
numberOfCol++;
printf("%lf", point[i][j]);
printf("\n");
++i;//go to next row/line
j = 0;//set back the column index to 0 aka the first column index
}//Repeat this process till you reach End of file
}
fclose(myfile);
printf("File Data..\n");
for (in = 0; in<i; in++)
{
for (jn = 0; jn<numberOfCol; jn++)
{
printf("%lf ",point[in][jn]);
}
printf("\n");
}
return 0;
}
編輯:這是一個由在comments.Thanks Hexasoft
#include<stdio.h>
//#pragma warning(disable : 4996)
int main()
{
int i=0, in = 0;
int j=0, jn = 0;
int numberOfCol = 0;
double num1,num2;
double point[65][2];
int result;
FILE *myfile=NULL;
myfile = fopen("test.txt", "r");
if (myfile == NULL)
{
printf("can not open file\n");
}
else
{
while (i<65)//65 or how may ever rows/lines of data you have in your file
{
result=fscanf(myfile, "%lf %lf", &num1, &num2);
if (result == 2)
{
point[i][j] = num1;
printf("%lf ", point[i][j]);
++j;
numberOfCol = j+1;
point[i][j] = num2;
printf("%lf", point[i][j]);
printf("\n");
++i;
j = 0;
}
else
{
printf("Format Error!\n");
}
if (feof(myfile))
{
printf("End of file reached!\n");
break;
}
}
}
fclose(myfile);
printf("File Data..\n");
for (in = 0; in<i; in++)
{
for (jn = 0; jn<numberOfCol; jn++)
{
printf("%lf ",point[in][jn]);
}
printf("\n");
}
return 0;
}
由hexasoft建議的檢查條件,修改後的代碼應檢查'fscanf'的'return'。並且也請顯示文件的格式的位。 – ameyCU
你可以發佈你的point.txt嗎? – danielfranca
我剛將65改爲14行文件,效果很好。我的point.txt文件:http://pastebin.com/NqtU0a3a – danielfranca