我有以下问题:-
编写一个程序,接受输入的名字和姓氏 用户并显示姓氏、逗号和首字母,后跟 按句号:
用户输入的名字前可能包含额外的空格, 在名字和姓氏之间,以及在姓氏之后。
我是这样写代码的:
#include <stdio.h>
#include<stdlib.h>
int main(void)
{
int i=0,j=0;
char name[100];
gets(name);
while( name[i] == ' ' || name[i] == '\t' )
i++;
while( *(name+i) != ' ' && *(name+i)!= '\t' )
i++;
while(name[i] == ' '|| name[i] == '\t')
i++;
while( *(name+i) != ' ' && *(name+i) != '\t' && *(name+i) != '\0' )
putchar(name[i++]);
putchar(',');
while( name[j] == ' '|| name[j] == '\t' )
j++;
while( *(name+j) != ' ' && *(name+j) != '\t' )
{
putchar(name[j++]);
break;
}
putchar('.');
return 0;
}
虽然它在工作,但它似乎在某种程度上是 Not Acceptable 。我该如何改进它?
最佳答案
避免使用 gets()
并使用 fgets()
。
来自手册页:
BUGS
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
编辑
您可以使用 ctype.h 中的 isalpha,isspace 函数来最小化您的代码。
isspace() :
检查空白字符。在“C”和“POSIX”语言环境中,它们是:空格、换页符('\f')、换行符('\n')、回车符('\r')、
水平制表符 ('\t') 和垂直制表符 ('\v')。
isalpha() :
检查字母字符;在标准的“C”语言环境中,它等同于 (isupper(c) || islower(c))。在某些地区,可能有
isalpha() 为真字母的附加字符,既不是大写也不是小写。
您可以使用此重构代码或代码的任何部分。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_LENGTH 100
int main(void)
{
int i=0,j=0;
char name[MAX_LENGTH];
fgets(name,MAX_LENGTH,stdin); //instead of gets(name);
for(i=0;i<strlen(name) ;i++) //loop to capture initial ,after this you have initial name[i]
if(isalpha(name[i]))
break;
for(j=i;j<strlen(name);j++) //loop to find start of last name
if(isspace(name[j]))
if(isalpha(name[j+1]))
break;
for(j=j+1;j<strlen(name);j++) //loop to print last name on screen
if(isalpha(name[j]))
putchar(name[j]);
else
break;
putchar(',');
putchar(name[i]); //print initial
putchar('.');
printf("\n");
return 0;
}
关于C- 字符串和循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18722036/