2015-09-21 38 views
0

我正在讀取一些有數據的.txt文件。我這樣做的「策略」只是逐行閱讀文件。我沒有任何問題做這個任務,但是,在某些時候,我有一個字符串與不同的數據(用空格分隔)。我只想讀取一些數據,因爲我不需要所有的數據。我用的sscanf從string.h中這樣做,這是什麼,我有一個例子:從字符串C讀取一些數據C

#include <stdio.h> 
#include <string.h> 

int main(void) { 
    char str[] = "1 189.37823 62.18428 2.486 25.33 -21.73 -21.68 -22.01 10.12 10.13 10.11 10.08 9.95 9.89 9.91 7 8.7 0 -42.85"; 

    int id, xid; 
    double z, r, d, sfr, tmp; 
    sscanf(str, "%d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", 
      &id, &z, &r, &d, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, 
      &tmp, &sfr, &xid, &tmp); 

    printf("id = %d, z = %lf, r = %lf, d = %lf, sfr = %lf, xid = %d\n", id, z, r, d, sfr, xid); 
} 

然而,我的解決方案是相當不雅,我只是「閱讀」的所有數據,併爲數據I不需要我使用時間變量。有沒有更正確(也許更有效)的方式來做到這一點?

+0

除其他細節,從sscanf的返回值(不是參數值)()需要檢查,以確保所有的輸入已成功讀取/轉換 – user3629249

回答

1

使用%*f來讀取實際值並將其刪除。

sscanf(str, "%d %lf %lf %lf %*f %*f %*f %*f %*f %*f %*f %*f %*f %*f %*f %*f %lf %lf %*f", 
      &id, &z, &r, &d, &sfr, &xid); 
+0

哇,我現在覺得很愚蠢。感謝你的回答!非常簡單的方法來解決我想要的:) – dpalma

-1

如果我們可以,只是忽略了最後一個,因爲它是沒有必要的, 則有:

sscanf(str, "%d %lf %lf %lf, &id, &z, &r, &d); 
for(int i = 0; i < 12; i++) // easy to control skip how many number 
    sscanf(str, "%lf, &tmp); 
sscanf(str, "%lf %lf", &sfr, &xid); 
+0

不,因爲傳遞給sscanf的'str'地址尚未更新。雖然這種技術可能用於讀取文件或讀取stdin(位置/文件指針更新位置),但對於內存'str'中的數據總是指向同一位置,因此每個sscanf()將重新讀取相同的數據 – user3629249