Что не так с этой программой на C?(Сканирование с терминала с помощью scanf) - PullRequest
0 голосов
/ 16 марта 2012

Программа просто строит, но подсказка просто зависает, как будто она застряла в бесконечном цикле.

Первый оператор printf даже не выполняется.

Идея программы состоит в том, чтобы взять MMSI, имя, позицию, курс и скорость и поместить их в структуру для записи в файл.

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;
}

Ответы [ 3 ]

1 голос
/ 16 марта 2012

Вы выделили корабль-> имя?

current_ship->name = malloc(51);

0 голосов
/ 16 марта 2012

Ваша проблема - пробелы в начале строк формата scanf.Ваша большая проблема - вообще использовать scanf.Просто используйте вместо этого fgets.

0 голосов
/ 16 марта 2012

Объявляется ли ship * getShipInfo() перед функцией main ()?Это может быть проблемой.

...