简体   繁体   中英

Trouble using fscanf to read coordinates in C

I know similar questions have been asked but none of them seemed to solve my problem. I get Segmentation fault (core dumped) when I run my code.

The first line in "data.dat" has the total number of points in the file and the next lines have the point coordinates (in 2 dimensions). I'm using fgets to read the first line and after that I'm using fscanf to read the next lines.

Here's my code:

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

int main(int argc, char *argv[]) {
    int n = atoi(argv[1]);
    FILE *fp;
    fp = fopen("data.dat","r");
    if (fp == NULL) {
        perror("Error");
    }

    int number;
    char str[3];

    fgets(str, 3, fp);
    number = atoi(str); // number of points to read from the file
    printf("number of lines: %d\n", number);

    // defining matrix to hold points
    float *P = (float *) malloc(sizeof(float)*2*number);

    int i = 0;
    while(i < number){
        int ret = fscanf(fp, "%f%f", P[i*number + 1], P[i*number + 2]);
        printf("%f  %f", P[i*number + 1], P[i*number + 2]);
        if (ret == 2){
            i++;
        }
    }
    fclose(fp);
    return 0;
}

Compiling this gives me no errors but it does give me the following warnings:

polynom.c: In function ‘main’:
polynom.c:32:24: warning: format ‘%f’ expects argument of type ‘float*’,but argument 3 has type ‘double’ [-Wformat=]

int ret = fscanf(fp, "%f%f", P[i*number + 1], P[i*number + 2]);
                    ^
polynom.c:32:24: warning: format ‘%f’ expects argument of type ‘float *’, but argument 4 has type ‘double’ [-Wformat=]

Which I don't really get because I did define argument 3 as float.

I run the code with a command line variable so the Segmentation fault is not because of that.

It should be

while (2 == fscanf(fp, "%f%f", &P[i], &P[i+1]) {
    i += 2;
    if (i >= number*2)
        break;
}

@Weather Vane well answered the major issue.

Below are additional points.

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

int main(int argc, char *argv[]) {
    // Check argc 
    if (argc < 1) Print_Error_And Quit();
    int n = atoi(argv[1]);
    FILE *fp;
    fp = fopen("data.dat","r");
    if (fp == NULL) {
        perror("Error");
    }

    int number;
    char str[3];

    // avoid naked magic numbers
    // fgets(str, 3, fp);
    fgets(str, sizeof str, fp);
    number = atoi(str); // number of points to read from the file
    printf("number of lines: %d\n", number);

    // defining matrix to hold points
    // No need for cast, avoid mis-match type/variable
    // float *P = (float *) malloc(sizeof(float)*2*number);
    float *P = malloc(2*number * sizeof *P);

    int i = 0;
    while(i < number){
        // int ret = fscanf(fp, "%f%f", P[i*number + 1], P[i*number + 2]);
        // reform
        int ret = fscanf(fp, "%f%f", &P[2*i], &P[2*i + 1]);
        // printf("%f  %f", P[i*number + 1], P[i*number + 2]);
        printf("%f  %f ", P[2*i], P[2*i + 1]);
        if (ret == 2){
            i++;
        }
        else {
          Likely_Should_Exit_Loop();
        }
    }
    fclose(fp);
    return 0;
}

You need to use the "%lf" specifier, if your variables are double , and you must pass the address of the variable to scanf() not the variable itself, like this

double value;

if (scanf("%lf", &value) == 1) 
{   /*        ^   ^ */
    /*        |   the address of operator. */
    /*       the correct speficier for `double' */
    fprintf(stdout, "%lf\n", value);
}

the malloc line is returning a pointer to an area that is large enough to hold 'number*2' floats. sound about right, but will not actually work correctly as there is no differentiation between one float and the next.

Suggest

struct twoFloat
{
    float float1;
    float float2;
};

then

struct twoFloat* P = malloc(sizeof(struct twoFloat)*number);
if ( NULL == P ) { // handle error and exit }

// implied else, malloc successful
....

then

    int ret = fscanf(fp, "%f%f", &P[i].float1, &P[i].float2);
    if (ret != 2) { // handle error and exit }

    // implied else, fscanf successful

    printf("%f  %f", P[i].float1, P[i].float2);
    i++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM