简体   繁体   中英

C - fscanf reading error

Just a heads up this is technically not a homework assignment. It is not worth a grade, and it just for practice. So do not think I am cheating to get a better grade.

Here is the function I am working in:

Car* readCars(char* filename) {
    FILE* fp = fopen( filename, "r" );

    if( fp == NULL ) {
        printf( "Error: Invalid File!" );
        exit(1);
    }

    Car cars[5];
    Car *carPtr;
    int i = 0;

    while( 1 ) {
        fscanf( fp, "%s %s %s %i", cars[i].color, cars[i].model, cars[i].brand, &cars[i].year );
        if( feof( fp ) ) {
            break;
        }
        i++;
    }

    carPtr = cars;

    fclose( fp );

    return carPtr;
}

Car struct:

typedef struct _car {
    char* color;
    char* model;
    char* brand;
    int year;
} Car;

At "return cars;" I am getting the "incompatible types when returning type 'struct Car *' when expecting 'Car'"

Here is where I am calling the function from main, and the declaration I have for the Car "object" in my mind.

Car *car;

car = readCars( carFileName );

1.) I am getting an error when scanning in from the file.

No space for the string in structure Car .

typedef struct _car {
    // char* color;
    char color[20];
    int year;
} Car;

if (2 != fscanf(fp, "%19s%d", cars[i].color, &cars[i].year) {
  break;
}

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