输入个数不限的数字,以逗号为分隔,以回车键为结束,排序后以4个数每行输出

/*
输入个数不限的数字,以逗号为分隔,以回车键为结束,数字大小在-32768-32767之间。从小到大排序后以4个数每行输出
如:
输入:12,34,-12,23,123,56,-9,789
输出:-12 -9 12 23
34 56 128 789
*/
#include <stdio.h>
#include<stdlib.h>
#include <string.h>

#define INITSIZE 100
#define INCREMENT 5

int my_atoi(char *s);

int main()
{
    char *s,*p,*q,*r;//输入字符串
    s=(char*)malloc(INITSIZE*sizeof(char));
    int *num;//排序后的字符串
    int i=0,j=0,m=0,n=0,length=0;
    printf("请输入以逗号为分隔符的字符串,回车表示结束:");
    //获取字符串长度
    while(1){
        if(i>=INITSIZE)//实现无限输入
        {
            s=(char*)realloc(s,(INITSIZE+INCREMENT)*sizeof(char));
        }
        s[i] = getchar();//逐个输入字符并赋值到字符串中。
        if(s[i] == '\n')//用回车表示输入结束
        {
            s[i]='\0';//修改为字符串结束符
            break;//退出循环。
        }
        i++;
    }
    length=strlen(s);//得到输入字符串的长度
    num=(int*)malloc(length*sizeof(int));//为数组申请空间
    i=0;
    p=s;
    while(i<length)
    {
        if(s[i]<-32768||s[i]>32767)
        {
            printf("数据非法!");
            system("pause");
            return 0;
        }
        if(s[i] == ','){
            i++;
            p++;
        }
        if(s[i] != ','){
            q=(char*)malloc(INITSIZE*sizeof(char));
            q=p;
            r=q;
            while(s[i] != ','&&s[i] != '\0'){
                i++;
                p++;
                q++;
            }
            q='\0';
            ++j;
            num[j]=my_atoi(r);//将字符串转化为数字,将数字存入数组,j从1开始,第一个位置空出来作为哨兵
        }
    }
    //直接插入排序
    for(m=2;m<=j;++m)
    {
        if(num[m]<num[m-1])
        {
            num[0]=num[m];//哨兵单元
            num[m]=num[m-1];
            for(n=m-2;num[0]<num[n];--n)
                num[n+1]=num[n];
            num[n+1]=num[0];
        }
    }
    //输出字符
    if(j>1){
        for(int k=1;k<=j;k++){
            printf("%d\t",num[k]);
            if(k%4==0)
                printf("\n");
        }
    }
    system("pause");
    return 0;
}

int my_atoi(char *q)
{
    int num, i;
    char ch;
    num = 0;
    for (i = 0; i<strlen(q); i++)
    {
        ch = q[i];
        if (ch < '0' || ch > '9')
            break;
        num = num*10 + (ch - '0');
    }
    return num;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值