2012-03-15 13 views
0

該程序只是建立,但提示只是像掛在無限循環掛起。這個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; 
} 
+1

終端是否處於阻止「stdout」被刷新的特殊模式?嘗試在printf()調用後插入'fflush(stdout)'。 – 2012-03-15 20:14:06

+0

你通過調試的方式嘗試了什麼?例如,如果'返回NULL;'作爲getShipInfo()中的第一個語句,程序是否會運行?像這樣的東西。 – 2012-03-15 20:14:28

+1

更好地發佈完整的代碼與船舶結構聲明和函數聲明等 – Jay 2012-03-15 20:49:27

回答

0

是否在ship * getShipInfo()之前聲明瞭main()函數? 這可能是一個問題。

+0

它聲明在一個頭文件,那不是問題 – 2012-03-15 20:12:41

+0

嗯,所以這不是一個完整的程序? – 2012-03-15 20:18:00

1

您是否分配了船名 - >名稱?

current_ship->name = malloc(51);

0

你的問題是在scanf函數的格式字符串開頭的空格。你更大的問題是使用scanf。只需使用fgets。