如何从数组中输入数据文件中的值?

时间:2014-10-18 15:29:58

标签: c arrays

我是一个完全的初学程序员,所以请耐心等待。

所以我有一个输入文本文件,我将在命令窗口中使用program.exe< data.txt中。文本文件有5行,每行有3个双精度值,如30.0 70.0 0.05等。

我想基本上使用结构数组来打印这些输入值,比如printf(“第一个值是%f”,数组[i] [0])。

到目前为止,这是我的错误代码:

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

#define MAXSOURCES 100

typedef struct {
    double x;
    double y;
} coordinates_t;

typedef struct {
    coordinates_t point;
    double w;
} soundsource_t;

coordinates_t a;
soundsource_t b;

int main(int argc, char *argv[]) {
    int i;

    while(scanf("%lf %lf %lf", &a.x, &a.y, &b.w) == 3) {
        soundsource_t soundsource[MAXSOURCES][2];
        for (i = 0; i <= MAXSOURCES; i++) {
            printf("%d", soundsource[i][0]);
            printf("%d", soundsource[i][1]);
            printf("%d", soundsource[i][2]);
            printf("\n");
        }
    }
    return 0;
}

有人可以帮我修复我的代码吗?感谢

2 个答案:

答案 0 :(得分:0)

要修复的示例

int main(int argc, char *argv[]) {
    soundsource_t soundsource[MAXSOURCES];
    int i, n = 0;

    while(scanf("%lf %lf %lf", &a.x, &a.y, &b.w) == 3) {
        soundsource[n].point = a;
        soundsource[n].w = b.w;
        n += 1;
    }
    for (i = 0; i < n; i++) {
        printf("%f,", soundsource[i].point.x);
        printf("%f ", soundsource[i].point.y);
        printf("%f\n",soundsource[i].w);
    }
    return 0;
}

答案 1 :(得分:0)

请务必阅读第一条评论。但是,您似乎需要学习更多内容,因此我将向您展示如何修改代码以实现此目的。

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

#define MAXSOURCES 100

typedef struct {
    double x;
    double y;
} coordinates_t;

typedef struct {
    coordinates_t point;
    double w;
} soundsource_t;

int main(int argc, char *argv[]) {
    int i, n = 0; // i is a counter and n will be the number of sources we actually read

    // we declare an array of sources, with size MAXSOURCES
    soundsource_t array[MAXSOURCES];

    /*
     * Now every cell of the array is a soundsource_t struct.
     * So, every cell is capable of storing a 'point' and a 'w'.
     */


    // We will read from stdin, three doubles per loop
    // and we will store them in the n-th cell of the array
    while(scanf("%lf %lf %lf", &(array[n].point.x), &(array[n].point.y), &(array[n].w)) == 3) {
        n++; // increment n, so that we keep track of number of sources we read
        if(n == MAXSOURCES) // we reached the limit, so stop reading
          break;
    }

    // print the sources we read. Notice that we go until n and not MAXSOURCES,
    // since we read n sources.
    for(i = 0; i < n; ++i) {
      // print the i-th cell
      printf("%lf %lf %lf\n", array[i].point.x, array[i].point.y, array[i].w);
    }

    return 0;
}

输出:

0.1 0.2 0.3
0.7 0.8 0.9
e <-- here I typed a letter to stop reading from input
0.100000 0.200000 0.300000
0.700000 0.800000 0.900000