Nick Maher
Nick Maher

Reputation: 3

Whats wrong with this C program? (Scanning from terminal using scanf)

The program just builds but the prompt just hangs like its stuck in an infinite loop.

The first printf statement is not even run.

The idea of the program is to take an MMSI, name, position, course and speed and put them in a struct for writing to a file.

int main(int argc, char** argv) {

    ship *current_ship;

    current_ship = getShipInfo();
    //writeShip(current_ship);

    return (EXIT_SUCCESS);
}
ship * getShipInfo() {
    ship *current_ship;
    current_ship = malloc(sizeof(ship));
    int MMSI, course;
    char name[51];
    float lat, lon, speed;

    printf("Enter MMSI (9 digits):\n"); 
    scanf(" %9d", &MMSI);

    printf("Enter ship name (upto 50 characters):\n");
    scanf(" %51s", name);

    printf("Enter ship latitude (real number with upto 3 decimal places):\n");
    scanf(" %f", &lat);

    printf("Enter ship longitude (real number with upto 3 decimal places):\n");
    scanf(" %f", &lon);

    printf("Enter course made good (degrees from true north):\n");
    scanf(" %3d", &course);

    printf("Enter speed over the ground (in knots with exactly one decimal place):\n");
    scanf(" %f", &speed);

    current_ship->MMSI = MMSI;
    strcpy(current_ship->name, name);
    current_ship->lat = lat;
    current_ship->lon = lon;
    current_ship->course = course;
    current_ship->speed = speed;

    return current_ship;
}

Upvotes: 0

Views: 510

Answers (3)

zvrba
zvrba

Reputation: 24574

Your problem are spaces at the start of scanf format strings. Your larger problem is using scanf at all. Just use fgets instead.

Upvotes: 0

perreal
perreal

Reputation: 98088

Have you allocated ship->name?

current_ship->name = malloc(51);

Upvotes: 1

samuirai
samuirai

Reputation: 772

Is ship * getShipInfo() declared before the main() function? This could be a problem.

Upvotes: 0

Related Questions