簡體   English   中英

從txt文件中讀取的C中的int數未知

[英]Read from txt file with unknown numbers of int in C

我必須從.txt文件中讀取“ N” int並將每個int放置到數組X [i]中,但問題是,我不願知道txt中有多少個int。 該代碼必須適用於遵循此模型的每個txt

5 4
1 2 3
1 3 4
2 3 5
4 5 5

所以我在第一行中有第二個數字(例如4),txt中的int數將為N = 4 * 3(4行包含3個數字(總是第二個數字* 3))+ 2(第一個線)
我知道怎么做的唯一代碼是當我知道有多少個數字時,例如

    int t[14] // I know there are 14 numbers on the .txt
    while(fgets(buf, sizeof(buf), fp)) {

  int result = sscanf(buf, "%d %d %d %d %d %d %d %d %d %d %d %d %d %d", &t[0], &t[1], &t[2], &t[3], &t[4], &t[5], &t[6],&t[7],&t[8],&t[9],&t[10], &t[11],&t[12],&t[13]);
  if (result <= 0) break;  // EOF, IO error, bad data

  for (r=0; r<result; r++) {
    if (i >= sizeof(X)/sizeof(X[0])) break;  // too many
    X[i++] = t[r]; //put them in the X[MAX]
  }
}  

我需要閱讀每個數字原因,例如
2 3 5
我將5放置到數組[2] [3]
我應該怎么做? 有人可以給我舉個例子嗎? 謝謝!

一個簡單的模板:

int a, b, i;
int *N;
if(fscanf(fp, "%d%d", &a, &b) != 2) { /* Read the first 2 integers */
    /* Unable to read in 2 integers. Handle error... */
}
N = malloc(3 * b * sizeof(int)); /* Allocate enough space */
for(i = 0; i < 3*b; ++i) {
    if(fscanf(fp, "%d", &N[i]) != 1) { /* Read numbers one-by-one */
        /* Input may not be enough. Handle error... */
    }
}
/* Now you have (3*b) integers stored in N */
/* after operations completed... */
free(N);

無需逐行閱讀並猜測有多少個數字。 只需一次又一次調用fscanf() ,因為您的輸入由空格和換行符分隔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM