2013-02-25 171 views
1

我在C++中編寫了一個應用程序,該應用程序需要一些命令行參數,其中第一個是整數,其餘三個是浮點數。的代碼與交易的部分看起來像這樣:如何擺脫這個命令行參數錯誤?

_tmain(__in int argc, __in PZPWSTR argv) 
{ 


    USHORT X, Y, Z, ZR, XR;       // Position of several axes 
    JOYSTICK_POSITION iReport;     // The structure that holds the full position data 
    BYTE id=1;          // ID of the target vjoy device (Default is 1) 
    UINT iInterface=1;        // Default target vJoy device 
    BOOL ContinuousPOV=FALSE;      // Continuous POV hat (or 4-direction POV Hat) 
    int count=0; 
    DOUBLE Xr, Yr, Zr; 


    // Get the ID of the target vJoy device 
    if (argc>1 && wcslen(argv[1])) 
     sscanf_s((char *)(argv[1]), "%d", &iInterface); 

    sscanf_s((char *)(argv[2]), "%d", &Xr); 
    sscanf_s((char *)(argv[3]), "%d", &Yr); 
    sscanf_s((char *)(argv[4]), "%d", &Zr); 

_tprintf("Acquired: X %d\nY %d\nZ %d\n", Xr, Yr, Zr); 

the rest of the code ...} 

我的問題是,當我寫

name.exe 1 15 16 17 

調用命令行程序,我得到XR = 15,但鋯= 16年僅僅是一些看似隨機的巨大負數。

我知道這可能是一些非常基本的錯誤,但我一直無法找到是什麼。感謝您的任何建議。

+0

這是預處理的'C++'嗎?爲什麼'main'不是'main'? – Rubens 2013-02-25 23:11:50

+1

@Rubens:這是MS特定的東西('_tmain'和''argv'的'PZWSTR')。 – 2013-02-25 23:16:04

回答

6

您需要使用%lf轉換才能讀取double。您目前使用的%d僅適用於int s。

+1

不完全是,'%f'是'float','%lf'是'double'。 – Hauleth 2013-02-25 23:17:16

+0

@ŁukaszNiemier:糟糕 - 很對。謝謝。 (對於不同於'scanf'的'printf'的不同類型轉換,總是會感到困惑]。 – 2013-02-25 23:19:14

+0

太棒了。謝謝。 – Sanuuu 2013-02-25 23:26:21