我正在尝试缩短要显示的字符串长度 (printf
)。例如我要求用户输入一个名字,然后程序将只显示后面的 15 个字符。
这是我的代码片段:
int score1=0,score2=0,foul1=0,foul2=0,rebound1=0,rebound2=0,assist1=0,assist2=0,missed1=0,missed2=0,choice1,choice2,choice4,choice5=0;
char choice3,home[15]="HOME",away[15]="AWAY";
printf("\t\t\t==================================\n\t\t\t|| NETBALL SCOREKEEPER\t||\n\t\t\t==================================\n\n");
do
{
printf("Do you want to enter teams' names?\n1-Yes\n2-No\n:>>");
scanf("%d",&choice1);
switch(choice1)
{
case 1:
{
do
{
printf("\nPlease enter HOME team's name(max 15 characters including space)\n:>>");
scanf(" %[^\n]s",&home);
printf("\nPlease enter AWAY team's name(max 15 characters including space)\n:>>");
scanf(" %[^\n]s",&away);
do
{
printf("\n\n%s VS %s\n\n1.Confirm\n2.Edit\n:>>",home,away);
scanf("%d",&choice2);
if(choice2!=1&&choice2!=2)
printf("\n***ERROR. INVALID INPUT***\n\n");
}
while (choice2!=1&&choice2!=2);
}
while(choice2==2);
break;
}
case 2:
{
printf("\nSet up to default:\n%s VS %s\n\n",home,away);
break;
}
default:
{
printf("\n***ERROR. INVALID SELECTION***\n\n");
break;
}
}
}
最佳答案
代码有输入输出问题;
char home[15]="HOME";
...
printf("Do you want to enter teams' names?\n1-Yes\n2-No\n:>>");
scanf("%d",&choice1);
...
printf("\nPlease enter HOME team's name(max 15 characters including space)\n:>>");
scanf(" %[^\n]s",&home);
...
Input1: "%[^\n]s"
中的's'
当然不需要了。 's'
不是 "%[^\n]"
格式说明符的一部分。
Input2:如果“最多 15 个字符”,则 home[15]
太小,无法保存 15 个 char
加上终止空字符 '\0'
。应该是 home[15+1]
。
Input3:代码没有限制用户输入为15,它只是要求用户限制输入。用户是邪恶的——不要相信他们会按要求限制输入。使用 "%15[^\n]");
将保存 char
的数量限制为 15。
Input4:使用 fgets()
进行用户输入要好得多。将用户输入读入一个合理大小的缓冲区,然后扫描它。
Input5:用 fgets()
编码 scanf()
是一个问题。 scanf("%d",&choice1);
通常在 stdin
中留下一个 '\n'
,即 fgets()
将仅使用它。
[编辑] Input6: ( @Cool Guy ) &home
应该是 home
。
输入解决方案 #1:快速但不稳健:
char home[15+1]="HOME";
...
printf("\nPlease enter HOME team's name(max 15 characters including space)\n:>>");
scanf(" %15[^\n]", home);
...
输入解决方案#2:更健壮:
char home[15+1]="HOME";
char buf[50];
...
printf("Do you want to enter teams' names?\n1-Yes\n2-No\n:>>");
fgets(buf, sizeof buf, stdin);
if (sscanf(buf, "%d",&choice1) != 1 || choice2 < 1 || choice2 > 2) {
printf("\n***ERROR. INVALID INPUT***\n\n");
break;
}
...
printf("\nPlease enter HOME team's name(max 15 characters including space)\n:>>");
fgets(buf, sizeof buf, stdin);
if (sscanf(buf, " %15[^\n]", home) != 1) {
Handle_BadNameInput(); // all spaces
}
...
输出:
要打印具有最大 char
数量的字符串,请使用 "%.*s"
printf("%.*s", max_Length, str);
可以添加更多检查:
1. 确保用户输入行中没有其他数据。
2. 检查 EOF。
关于c - 在 C 中缩短字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28392408/