C- 字符串和循环

标签 c loops arrays

我有以下问题:-

编写一个程序,接受输入的名字和姓氏 用户并显示姓氏、逗号和首字母,后跟 按句号:

用户输入的名字前可能包含额外的空格, 在名字和姓氏之间,以及在姓氏之后。

我是这样写代码的:

#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/

相关文章:

c - 指向字符串的指针不递增(C 编程)

c - 在 C 中将字符串转换为 morze 时 Printf() 不起作用

c - 二维阵列动态分配中的段错误

javascript - 从本地存储收集数组时出现 "JSON.parse"问题

c - 为什么内存地址在一个地方上升而在另一个地方下降?

python - 如何找到netCDF数组除零之外的最小值

c - 去掉程序中的 break 语句

loops - 循环嵌套循环,但限制更多一点

javascript - 使用javascript选择另一个选项后循环隐藏选项不起作用

c# - 提高 C# 循环的效率