2017-03-22 57 views
0
token1 = strtok(udtAddressVar.strName, " "); 
strcpy(udtAddressVar.strFirstName, token1); 
token1 = strtok(NULL, " "); 
strcpy(udtAddressVar.strMiddleName, token1); 
token1 = strtok(NULL, " "); 
strcpy(udtAddressVar.strLastName, token1); 

使用此代碼但在沒有中間名時失敗。例如,對於「約翰·亨利·藍」,而不是爲了工作正常,「布拉德·亨利如果在C語言中爲空,則跳過中間名

+0

您是否嘗試過爲每個變量設置默認值?我的意思是,strFirstName,strMiddleName和strLastName在開始時具有NULL值,嘗試將它們全部初始化爲空字符串,例如「」,因爲我認爲由於在參數中放置了空值而導致出現錯誤。 –

+0

它們都被初始化爲空字符串。 – Coder

回答

0

與大多數事情一樣,它總是測試一個函數的結果以確保它完成了您認爲的功能是一個好主意。通過這樣做,你也可以解決你的問題。

token1 = strtok(udtAddressVar.strName, " "); 
if(token1) 
    { 
    strcpy(udtAddressVar.strFirstName, token1); 
    token1 = strtok(NULL, " "); 
    if(token1) 
    { 
    strcpy(udtAddressVar.strMiddleName, token1); 
    token1 = strtok(NULL, " "); 
    if(token1) 
     { 
     strcpy(udtAddressVar.strLastName, token1); 
     } 
    else 
     { 
     strcpy(udtAddressVar.strLastName, udtAddressVar.strMiddleName); 
     *udtAddressVar.strMiddleName='\0'; 
     } 
    } 
    } 

您還可以擴展此更進一步處理您也有2個或更多中間名的情況。

+0

謝謝克里斯,它工作:) – Coder

0

檢查token1是空嘗試讀取姓前:

// get the first token 
token1 = strtok(udtAddressVar.strName, " "); 
strcpy(udtAddressVar.strFirstName, token1); 

// middle name 
token1 = strtok(NULL, " "); 
strcpy(udtAddressVar.strMiddleName, token1); 

// Check if the last name exists 
if (token1 == NULL) { 
    udtAddressVar.strLastName = udtAddressVar.strMiddleName; 
    udtAddressVar.strMiddleName = ""; 
} 
// get the last name 
else { 
    token1 = strtok(NULL, " "); 
    strcpy(udtAddressVar.strLastName, token1); 
} 
0
token1 = strtok(udtAddressVar.strName, " "); 
strcpy(udtAddressVar.strFirstName, token1); 
token2 = strtok(NULL, " "); 
token3 = strtok(NULL, " "); 
if (token3) { 
    strcpy(udtAddressVar.strMiddleName, token2); 
    strcpy(udtAddressVar.strLastName, token3); 
} else { 
    udtAddressVar.strMiddleName[0] = '\0'; 
    strcpy(udtAddressVar.strLastName, token2); 
}