【问题标题】:I need to read x and y values from .txt file in C我需要从 C 中的 .txt 文件中读取 x 和 y 值
【发布时间】:2016-08-06 11:45:27
【问题描述】:

我需要从文本文件中读取 x 和 y 坐标,然后将它们用于多项式回归。我可以做回归部分,但我无法从文件中读取值。数据点是

5,10,15,20,25,30,35,40,45,50

17,24,31,33,37,37,40,40,42,41

第一行是x,第二行是y,在txt文件中就是这样写的。

从另一个问题,我设法将所有数字读入一个 20 的 x 数组,但我真的需要将它们放在单独的数组中,如 x 和 y。我怎样才能做到这一点? 这是我当前的代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *data;
data = fopen("data.txt", "r");

int x[20];
int i=0;


for(i=0; i<20; i++)
    fscanf(data, "%d,", &x[i]);


for(i=0; i<20; i++)
printf("x are: %d\n", x[i]);


fclose(data);
return 0;
}

提前致谢。

【问题讨论】:

  • 为什么不对另一个数组使用类似的循环:int y[20]; for(i=0; i&lt;20; i++) fscanf(data, "%d,", &amp;y[i]);?您还需要考虑如果每行中的数字更少或更多会发生什么,并添加错误检查等。
  • 每行总是10个元素吗?

标签: c file text


【解决方案1】:

如您在问题中所述,如果您始终在一行中有 10 个 int,而在另一行中有 10 个 int,则可以再使用一个数组 int y[10]; 来存储 y 值。并使用两个for 循环 - 一个用于读取 10 x 值,另一个用于读取 10 y 值。你的两个数组只需要存储10 元素。

    int x[10];
    int y[10];  // Array to store y values
    int i=0;

    for(i=0; i<10; i++) // Read first 10 values to x array
            fscanf(data, "%d,", &x[i]);

    for(i=0; i<10; i++) // Read next 10 values to y array
            fscanf(data, "%d,", &y[i]);

    for(i=0; i<10; i++)
            printf("x are: %d\n", x[i]);

    for(i=0; i<10; i++)
            printf("y are: %d\n", y[i]);

但是,如果有可能在这些行中可能存在不同数量的整数 - 多于或少于 10 - 那么您将需要进行更多检查。

【讨论】:

    【解决方案2】:

    检查是否存在逗号

    int x[20], y[20];
    int i, n;
    char tail;
    
    for(i = 0; i < 20 && 2 == fscanf(data, "%d%c", &x[i], &tail); i++){
        if(tail != ',')
            break;
    }
    n = i+1;//if(n > 20){ puts("bad format!"); return -1;}
    
    for(i = 0; i < n; i++)
        fscanf(data, "%d,", &y[i]);
    
    fclose(data);
    
    for(i = 0; i < n; i++)
        printf("(%d, %d)\n", x[i], y[i]);
    

    【讨论】:

      【解决方案3】:

      首先,我建议您成对编写xy 值(似乎更合乎逻辑,因此更易于实现)。例如:

      1 2
      3 4
      5 6
      

      所以fscanf(FILE* fp, char* format,...)

      • FILE* fp - 指向要从中读取数据的流的指针(甚至可以是标准的stdin,这使得fscanf() 可以作为scanf() 工作);

      • char* format - 格式化字符串(例如:"%d%s%d");

      • ... - 将接收输入数据的内存中变量和/或区域的地址。变量数量由char* format指定。

      您使用fscanf(data, "%d,", &amp;x[i]); 而不是使用fscanf(data, "%d%d", &amp;x[i],&amp;y[i]); 忘记了您获得的数据与您在char* format 中指定的一样多。

      另请注意,fscanf()scanf() 返回成功输入数据的数量,这意味着您可以执行以下操作:

      while(fscanf(data,"%d%d",&x[i],&y[i]) == 2) {
          // do something, or don't
      }
      

      您可以将while 留空。最后,您将获得存储在单独数组中的 xy 点。发生的情况是fscanf() 尝试读取两个整数值。如果他设法做到这一点,他会返回成功输入数据的数量,即 2。否则,他会返回 1(如果您错过了 xy)或 0(如果它是文件结尾)。

      【讨论】:

        猜你喜欢
        • 2020-10-03
        • 2022-11-19
        • 1970-01-01
        • 2020-10-09
        • 2021-07-17
        • 2019-07-26
        • 1970-01-01
        • 1970-01-01
        • 2021-10-29
        相关资源
        最近更新 更多