上述代碼,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
唯一problemI SE在這個代碼是語義@chqrlie。如果該人沒有中間名,但只輸入姓氏和名字,那麼姓氏的含義被解釋爲「中間」。 – user3078414
@ user3078414:我不確定你在評論中的含義。如果用戶只輸入一個只有2個部分的名字,那麼'sscanf()'只能轉換'first'和'middle',並且*標準名稱*會被打印爲'first'和full'middle'的首字母,這真的是最後一個名字。重命名這3個數組'part1','part2'和'part3'將減少潛在的混淆。 – chqrlie
感謝您的迴應,@ chqrlie。我正在考慮可能組織數據並準備將其複製到任何數據庫所需的代碼。我不相信有人需要這樣的代碼來提供'printf()'。 ( - : – user3078414