我有一个文件examplefile.txt,里面有如下数据:

0.000 3.142
3.142 4.712
4.712 1.571

我试图只读取第二列中的值。为了做到这一点,我一直在使用以下代码。
#include <stdio.h>
#include <float.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

int main(int argc, const char * argv[])
{
    double tempvalue;
    int a,b;

    FILE *file;
    char *myfile=malloc(sizeof(char)*80);
    sprintf(myfile,"examplefile.txt");
    if (fopen(myfile,"r")==NULL)
    {

    }
    else
    {
        file=fopen(myfile,"r");
        for (a=0;a<3;a++)
        {
            for (b=0;b<2;b++)
            {
                printf("a=%d\n",a);
                fscanf(file,"%lf",&tempvalue);
                if (b==1)
                {
                    printf("%lf\n",tempvalue);
                }
            }
        }
    }
}

但是,每次只返回值1.571。我无法存储所有值,因为我正在使用的实际文件包含太多值,无法存储。我还没有找到解决这个问题的办法。

最佳答案

我建议两者都读,而忽略第一个。像这样的东西

#include <stdio.h>
int main() {
    float v1, v2;
    FILE* file = fopen(myfile, "r");
    if (file == NULL) {
        perror("open failed");
        return -1;
        }
    while(fscanf(file, "%f %f", &v1, &v2) == 2) {
        print("read %f\n", v2);
        }
    return 0;
    }

10-08 00:16