2013-08-27 98 views
0

我目前正在研究一些代碼,我知道它有什麼問題。我的代碼提示用戶輸入一個名稱,並使用fgets() or sscanf()將其作爲字符串存儲。如果用戶輸入錯誤的東西(即數字或字母數字的情況),它應該打印錯誤消息並再次要求輸入,直到用戶輸入權限。此外,我已經初始化:我如何解決這個while循環嵌套在if-else中?

char name [47];

printf ("Name: "); 

//some code dealing with newline character with the use of fgets 

if ((sscanf (name, %s, name)) == 1) 
    //some code dealing with this condition 
else { 
    do { 
     printf ("ERROR: Invalid name. Name should consist of letters only.\n"); 
     printf ("Name: "); 
     if (fgets (name, sizeof (name), stdin) == '\0') 
      //some code dealing with EOF 
    } while ((sscanf (name, %s, name)) != 1); 
} 

誰能告訴我有什麼不對?

+0

你正在''s''周圍缺少名字。 – Barmar

回答

1
char name[47]; 
char line[4096]; 

while (printf("Name: ") > 0 && fgets(line, sizeof(line), stdin) != 0) 
{ 
    if (sscanf(line, "%46s", name) != 1) 
     ...empty line?... 
    else if (valid_name(name)) 
     break; 
    printf("Error: invalid name (%s). Name should consist of letters only.\n", name); 
} 

您忘了printf()是否返回打印的字符數?那麼,大多數人不會經常測試它的結果,但在這種情況下這樣做是有用的。測試可能是!= 6而不是僅僅> 0,但是在實踐中可能都可以正常工作。

請注意,使用"%46s"可將值讀入name而不會有緩衝區溢出的風險。請注意,sscanf()不會將換行符讀入name