![](/img/trans.png)
[英]How to read and store 2 float values seperated by a comma from a file into two arrays where each float is stored in one array
[英]How to move values from a CSV file to a float array?
我有一個.csv
文件,格式如下:
24.74,2.1944,26.025,7.534,9.317,0.55169 [etc]
我想將浮點值移動到浮點數數組中。
該數組如下所示:
fValues[0] = 24.74
fValues[1] = 2.1944
fValues[2] = 26.025
fValues[3] = 7.534
fValues[4] = 9.317
[etc]
我要處理1000個數字。
完成此任務的代碼是什么?
這是我得到的代碼中最接近的代碼:
int main()
{
FILE *myFile;
float fValues[10000];
int n,i = 0;
myFile = fopen("es2.csv", "r");
if (myFile == NULL) {
printf("failed to open file\n");
return 1;
}
while (fscanf(myFile, "%f", &fValues[n++]) != EOF);
printf("fValues[%d]=%f\n", i, fValues[5]); //index 5 to test a number is there.
fclose(myFile);
return 0;
}
另外,當我運行此代碼時,我會收到退出代碼3221224725
。
這是與內存訪問相關的問題/堆棧溢出嗎?
我的環境:
從文件中讀取時,您不會跳過文件中的逗號。
對fscanf
的第一次調用通過%f
格式說明符讀取float
。 在隨后的讀取中,文件指針位於第一個逗號,並且不會超出該范圍,因為您仍在嘗試讀取浮點數。
您需要在循環內添加對fscanf
的單獨調用以使用逗號:
while (fscanf(myFile, "%f", &fValues[n++]) == 1) {
fscanf(myFile, ",");
}
另外,您沒有初始化n
:
int n,i = 0;
然后,當您嘗試增加它的值,從而讀取一個未初始化的值時,您將調用未定義的行為 。 像這樣初始化它:
int n = 0, i = 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.