在C语言中,如果要输入一串数字,其中每个数字用逗号隔开,且不知道总共输入了多少数字。要怎样输入呢?

例如:输入“14,24,32,23,2345,10”怎样把各个数字赋值到数组中,或者是变量中

先读1个整型数。
然后循环:读1个字符,如果字符是逗号则读1个整型数,如果不是逗号,循环就结束。
如果读整型数有错,循环也结束。
#include<stdio.h>
#include<stdlib.h>
main(){ int x[100],n=0,i;
int c;
if ( scanf("%d",&x[n])==1) n++;
while(1){
scanf("%c",&c);
if (c != ',') break;
if ( scanf("%d",&x[n])==1) n++;else break;
}
printf("\nI read: ");
for (i=0;i<n;i++) printf("%d ",x[i]);
return 0;
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2013-03-29
比较麻烦。
可以每次malloc int
可以规定以一个特定的字符结束,比如当输入#号的时候代表输入结束
第2个回答  2013-03-29
#include <stdio.h>
#define MAX_SIZE 10000 //输入数的上限
#define END_NUM -1 //作为输入结束符,这个数要保证不跟正常要处理的数冲突
int main(void)
{
int count, num[MAX_SIZE];

count = 0; //保存输入数的个数
while (scanf("%d%*c", &num[count]) && (num[count] != END_NUM)) //输入-1表示输入结束
++count;

return 0;
}
相似回答