我想用“fscanf”匯入數字(總共 40000 個,以空格分隔)(格式:2.000000000000000000e 02)并將其放入一維陣列中。我嘗試了很多東西,但我得到的數字很奇怪。
到目前為止我所擁有的:
int main() {
FILE* pixel = fopen("/Users/xy/sample.txt", "r");
float arr[40000];
fscanf(pixel,"%f", arr);
for(int i = 0; i<40000; i )
printf("%f", arr[i]);
}
我希望有人可以幫助我,我是初學者;-) 非常感謝!!
uj5u.com熱心網友回復:
代替:
fscanf(pixel,"%f", arr);
這與此完全等效,并且僅讀取一個值:
fscanf(pixel,"%f", &arr[0]);
你要這個:
for(int i = 0; i<40000; i )
fscanf(pixel,"%f", &arr[i]);
完整代碼:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* pixel = fopen("/Users/xy/sample.txt", "r");
if (pixel == NULL) // check if file could be opened
{
printf("Can't open file");
exit(1);
}
float arr[40000];
int nbofvaluesread = 0;
for(int i = 0; i < 40000; i ) // read 40000 values
{
if (fscanf(pixel,"%f", &arr[i]) != 1)
break; // stop loop if nothing could be read or because there
// are less than 40000 values in the file, or some
// other rubbish is in the file
nbofvaluesread ;
}
for(int i = 0; i < nbofvaluesread ; i )
printf("%f", arr[i]);
fclose(pixel); // don't forget to close the file
}
免責宣告:這是未經測驗的代碼,但它應該讓您了解您做錯了什么。
uj5u.com熱心網友回復:
您需要fscanf()回圈呼叫。你只是在讀一個數字。
int main() {
FILE* pixel = fopen("/Users/xy/sample.txt", "r");
if (!pixel) {
printf("Unable to open file\n");
exit(1);
}
float arr[40000];
for (int i = 0; i < 40000; i ) {
fscanf(pixel, "%f", &arr[i]);
}
for(int i = 0; i<40000; i ) {
printf("%f", arr[i]);
}
printf("\n");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/363016.html
