[英]In C, how do I read a file, and store only the doubles - ignoring text before?
我需要讀入一個包含文本的文件,然后再為該文本加倍。 僅僅是獲得一組數字的均值和標准差,因此前面的文本是無關緊要的。 例如,我的輸入文件看起來像:
preface 7.0000
chapter_1 9.0000
chapter_2 12.0000
chapter_3 10.0000
等等..
在這種情況下,它正在尋找書各章的平均值和標准開發。 我在下面的代碼部分中,但是我不太確定如何“忽略”文本,僅獲取雙精度。 此刻此代碼打印出零,並且僅在超出數組限制時才退出循環,在程序開始時我將其設置為常數20。
FILE *ifp;
char *mode = "r";
ifp = fopen("table.txt", mode);
double values[array_limit];
int i;
double sample;
if (ifp==NULL)
{
printf("cannot read file \n");
}
else
{
i = 0;
do
{
fscanf(ifp, "%lf", &sample);
if (!feof(ifp))
{
values[i] = sample;
printf("%.4lf \n", values[i]);
i++;
if (i>=array_limit) //prevents program from trying read past array size limit//
{
printf("No more space\n");
break;
}
}
else
{
printf("read complete\n");
printf("lines = %d\n", i);
}
}while (!feof(ifp));
fclose(ifp);
}
我認為您可以使用fscanf(ifp, "%*[^ ] %lf", &sample)
從文件中讀取。 *
表示忽略該特定匹配, []
指定要匹配的字符列表,而^
表示匹配除[]
中的所有字符。
或者可能(稍微簡單一些) fscanf(ifp, "%*s %lf", &sample)
。
您有兩個主要問題-您使用的feof 總是很錯誤 ,並且您沒有檢查fscanf
的返回值,它告訴您是否有值(或是否有價)。 eof)。
所以你想要的是
while ((found = fscanf(ifp, "%lf", &values[i])) != EOF) { /* loop until eof */
if (found) {
/* got a value, so count it */
if (++i >= ARRAY_LIMIT) {
printf("no more space\n");
break;
}
} else {
/* something other than a value on input, so skip over it */
fscanf(ifp, "%*c%*[^-+.0-9]");
}
}
從文件讀fgets
,通常最好是使用fgets
讀取一行,然后使用sscanf
提取您感興趣的部分:
#include <stdlib.h>
#include <stdio.h>
#define ARRAY_LIMIT 10
#define LINE_LENGTH 128
int main()
{
double values[ARRAY_LIMIT];
int i, count = 0;
double sample;
FILE *ifp = fopen("table.txt", "r");
if (ifp==NULL)
{
printf("cannot read file \n");
return 1;
}
char buff[LINE_LENGTH];
while (fgets(buff, LINE_LENGTH, ifp) != NULL)
{
if (sscanf(buff, "%*s %lf", &sample) != 1) break;
values[count++] = sample;
if (count == ARRAY_LIMIT) {
printf("No more space\n");
break;
}
}
fclose(ifp);
for (i = 0; i < count; ++i) {
printf("%d: %f\n", i, values[i]);
}
return 0;
}
如果fgets
遇到文件末尾或發生讀取錯誤,則返回NULL
。 否則,它將文件的一行讀入字符緩沖區buff
。
sscanf
的星號%*s
表示將sscanf
該行的第一部分。 第二部分寫入變量sample
。 我正在檢查sscanf
的返回值,該值指示已成功讀取了多少個值。
當到達文件末尾或計數達到數組大小時,循環中斷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.