c - 在 C99 中读取制表符分隔的数据

标签 c file input io c99

我可以给我的程序输入文件如下:

1     0     0     0     2    -1
16    70  -169  -580    75
1     0     4     0    -5
0    -9     3     5    -3
5    -4     3    -2     0
1.0   -3.4    5.4531   -4.2077    1.5092   -0.2030

每一行代表一个多项式。例如,第一行表示 x^6 + 2x^2 - 1

我正在尝试阅读此文件,但不确定如何处理制表符和换行符。我也不确定如何处理系数和多项式的数量可以改变的事实。

现在我有:

polynomial** readPolyFile(FILE *polyFile){
    polynomial *p = NULL; 
    int size = 1; /* Size to malloc */
    polynomial **polynomials = NULL; 

    polyList = malloc(sizeof(polynomial*) * size); /* Initialize */

    if(polyList == NULL){
        fprintf(stderr, "%s %n: Could not allocate memory\n", __FILE__, __LINE__);
        exit(-99); 
    }

    /* Read all of the data from the file */
    do {

    }

}

我最初的想法是每次需要时都增加大小,但我不确定这是否是解决此问题的最佳方法。

我对多项式的定义如下:

typedef struct
{
    unsigned int nterms;       /* number of terms */
    double complex *polyCoef;  /* coefficients    */
} polynomial;

我想返回一个多项式结构列表。关于如何解决这个问题有什么建议吗?

最佳答案

Any suggestions on how to go about this?

将输入读入链表,完成后形成数组。


一些快速代码,缺乏必要的错误检查,让你开始。

建立一个空链表

typedef struct LL {
  polynomial *poly;
  struct LL *next;
} LL;
LL head = { NULL, NULL };
LL *p = &head;

在循环内,读取缓冲区中的一行,将其解析为多项式并附加到 LL。

#define N 1000
count = 0;
char buf[N];
/* Read all of the data from the file */
while (fgets(buf, sizeof buf, polyFile)) {
  p->next = malloc(sizeof *(p->next));
  p = p->next;

  // TBD code for OP.
  // Hint: degree of polynomial < sizeof buf/2
  p->poly = polyList_from_line(buffer);

  p->next = NULL;
  count++;
}

为数组分配

polyList = malloc(sizeof *polyList * count);
p = head.next;
for (i=0; i< count; i++) {
  assert(p);
  polylist[i] = p->poly;
  next = p->next;
  free(p);
  p = next;
}

return polylist;

子问题:更多读取制表符分隔数据的伪代码

  polynomial *polyList_from_line(char *buffer) {
    double complex coef[some factor of N];
    count = 0;

    char *token = strtok(buffer, "\t");
    while (token)  {
      // parse the token for a complex number
      if (sscanf(buffer, tbd_format, tbd_variables) != expected_result)
        break;
      coef[count++] = ...
      token = strtok(tbd_code);
    }
    // Malloc polynomial using count
    // Populate polynomial from coef[]
    // return allocation
  }

关于c - 在 C99 中读取制表符分隔的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221139/

相关文章:

c - 在 char 数组和掩码中使用 int 而不是 char

java - 如何从 Java 打开文件? (具体来说是一个.bat文件)

c - 文件与数组,哪个更快?

c# - 如何将 textbox.text 转换为 int 或仅用于 int 输入的内容?

java - 将文件读入数组返回错误的元素

python - 将字符串作为资源嵌入

c - C语言中EDOM和ERANGE的区别?

c - 我怎么知道指针中有多少空闲位?

python - 从python中的文件中读取逗号分隔的元组

python - 如何将输入读取为数字?