这个C程序有什么问题吗? (使用scanf从终端扫描)

时间:2012-03-15 20:06:27

标签: c scanf

该程序刚刚构建,但提示只是像它陷入无限循环一样挂起。

第一个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 个答案:

答案 0 :(得分:1)

您是否已分配ship->名称?

current_ship->name = malloc(51);

答案 1 :(得分:0)

在main()函数之前声明了ship * getShipInfo()吗? 这可能是个问题。

答案 2 :(得分:0)

您的问题是scanf格式字符串开头的空格。你遇到的更大问题是使用scanf。只需使用fgets。