gpt4 book ai didi

c - 以标准格式打印名称

转载 作者:太空狗 更新时间:2023-10-29 16:01:03 25 4
gpt4 key购买 nike

我正在尝试开发一个以您的名字为基础并以标准格式提供输出的基本程序。问题是我希望用户可以选择不添加中间名。

例如:Carl Mia Austin 给我 C. M. Austin 但我希望即使输入是 Carl Austin 它也应该给我 C. Austin 而无需询问用户是否有中间名。那么,有没有一种方法或功能可以自动检测到它?

#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;
}

最佳答案

按照目前的写法,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;
}

请注意,现实生活中的名字可能会更加通用:想想带有多字节字符的外国名字,或者甚至只是William Henry Gates III,也称为 Bill Gates。上面的代码处理了后者,但没有处理这一个:Éléonore de Provence,英格兰国王亨利三世的年轻妻子,1223 - 1291。

关于c - 以标准格式打印名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38557112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com