您的位置:首页 > 其它

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

2017-03-29 16:31 302 查看
/*
输入个数不限的数字,以逗号为分隔,以回车键为结束,数字大小在-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("pau
4000
se");
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)
num[n+1]=num
;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐