2016-07-24 44 views
3

我正在嘗試開發一個基本程序,它以您的名字和標準格式提供輸出。問題是我希望用戶有一個不添加中間名的選項。以標準格式打印名稱

例如:卡爾米婭奧斯汀給我C.M.奧斯汀,但即使輸入是卡爾奧斯汀,它也應該給我C.奧斯汀,而不詢問用戶是否有中間名。 那麼,有沒有一種方法或功能可以自動檢測?

#include <stdio.h> 

int main(void) { 
    char first[32], middle[20], last[20]; 

    printf("Enter full name: "); 
    scanf("%s %s %s", first, middle, last); 
    printf("Standard name: "); 
    printf("%c. %c. %s\n", first[0], middle[0], last); 

    return 0; 
} 

回答

7

上述代碼,scanf("%s %s %s", first, middle, last);預計3個部分鍵入,並且會等到用戶鍵入他們。

你想讀一個線路輸入與fgets()和掃描,對於名稱部分與sscanf並指望有多少部分被轉換:

#include <stdio.h> 

int main(void) { 
    char first[32], middle[32], last[32]; 
    char line[32]; 

    printf("Enter full name: "); 
    fflush(stdout); // make sure prompt is output 
    if (fgets(line, sizeof line, stdin)) { 
     // split the line into parts. 
     // all buffers have the same length, no need to protect the `%s` formats 
     *first = *middle = *last = '\0'; 
     switch (sscanf(line, "%s %s %[^\n]", first, middle, last)) { 
     case EOF: // empty line, unlikely but possible if stdin contains '\0' 
     case 0: // no name was input 
      printf("No name\n"); 
      break; 
     case 1: // name has a single part, like Superman 
      printf("Standard name: %s\n", first); 
      strcpy(last, first); 
      *first = '\0'; 
      break; 
     case 2: // name has 2 parts 
      printf("Standard name: %c. %s\n", first[0], middle); 
      strcpy(last, middle); 
      *middle = '\0'; 
      break; 
     case 3: // name has 3 or more parts 
      printf("Standard name: %c. %c. %s\n", first[0], middle[0], last); 
      break; 
     } 
    } 
    return 0; 
} 

注意,名稱可以在現實生活中多一點多才多藝:想想外國人的多字節字符,甚至簡單地稱爲比爾蓋茨(Bill Gates)。上面的代碼處理後者,但不是這一個:Éléonore de Provence,亨利三世,英格蘭國王,1223年輕的妻子 - 1291

+0

唯一problemI SE在這個代碼是語義@chqrlie。如果該人沒有中間名,但只輸入姓氏和名字,那麼姓氏的含義被解釋爲「中間」。 – user3078414

+0

@ user3078414:我不確定你在評論中的含義。如果用戶只輸入一個只有2個部分的名字,那麼'sscanf()'只能轉換'first'和'middle',並且*標準名稱*會被打印爲'first'和full'middle'的首字母,這真的是最後一個名字。重命名這3個數組'part1','part2'和'part3'將減少潛在的混淆。 – chqrlie

+0

感謝您的迴應,@ chqrlie。我正在考慮可能組織數據並準備將其複製到任何數據庫所需的代碼。我不相信有人需要這樣的代碼來提供'printf()'。 ( - : – user3078414

0

您可以使用isspace,並在名稱查找空間:

#include <stdio.h> 
#include <ctype.h> 

int main(void) 
{ 
    char first[32], middle[32], last[32]; 
    int count=0; 
    int i = 0; 
    printf("Enter full name: "); 
    scanf(" %[^\n]s",first); 
    for (i = 0; first[i] != '\0'; i++) { 
     if (isspace(first[i])) 
      count++; 
    } 
    if (count == 1) { 
     int read = 0; 
     int k=0; 
     for (int j = 0; j < i; j++) { 
      if (isspace(first[j])) 
       read++; 
      if (read > 0) { 
       last[k]=first[j]; 
       k++; 
      } 
     } 
     last[k+1] = '\0'; 
    } 
    printf("Standard name: "); 
    printf("%c. %s\n", first[0], last); 

    return 0; 
} 

測試

Enter full name: Carl Austin 
Standard name: C. Austin 
+0

我想你也應該測試兩個名字會發生什麼 – usr2564301

+0

你的'scanf'模式中存在一個「s」,但也許最好是使用'fgets'。 – anatolyg