C语言,目的:输入一串数字,用空格隔开,然后赋值给数组

#include<stdio.h>
void main()
{
int space=0,c;
printf("please input some number");
while((c=getchar())!='\n')
if (c==' ')
space++;
int a[space+1],i;
for(i=0;i<space+1;i++)
scanf("%d",&a[i]);
}
目的:输入一串数字,用空格隔开,然后赋值给数组,能怎么改下?

#include<stdio.h>
void main()
{
int space=0,temp;
char            c  ;
int a[100],i,flag;
     temp = 0 ;
     printf("please input some number,less than 100");
while((c=getchar())!='\n')
{    if (c==' ')
     {
          a[space] = temp ; 
          space++;
          temp = 0 ;
          flag = 0 ;
     } 
     else
     {
         flag = 1 ;
         temp = temp*10 + (c-48)  ;  // 将字符数字C转换为实际数字C
     }
}

if(flag)                       //如果回车键之前为非空格,则该数也要存入数组
{
   a[space] = temp ; 
}

for(i=0;i<space+1;i++)
pringtf("a[%0d] = %8d",i,a[i]);

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-08-26
你这程序编译都没办法通过, c语言定义数组大小时不允许有变量, 因为数组是静态结构.
第2个回答  2013-08-26
我用的是GCC编译器 就把main函数的返回值改成int然后再在main函数中加个return就可以了
第3个回答  推荐于2018-02-27

你的程序和你的题目相差悬殊呀,我想你的本意应该是:

输入:123  456  789 ,然后分割赋值

    a[0] = 123;

    a[1] = 456;

    a[2] = 789;

是这个意思吧

#include<stdio.h>
#include<string.h>
int main(void)
{
char a[100];
char c[] = " ";
printf("请输入一串数字:");
gets(a);

    printf("分割后的数字是:\n");

printf("%s\n",strtok(a,c));
char *p = strtok(NULL,c);
while(p)
{
printf("%s\n",p,c);
p = strtok(NULL,c); 
}
return 0;
}

本回答被提问者和网友采纳
第4个回答  2013-08-26
你要求这个数组的大小恰好等于输入的数字个数么?
相似回答