[英]Input a dynamic length array in C using scanf
I have to input an array of integers. 我必须输入一个整数数组。 The length of this array is determined at runtime when the user hits some sentinal key (likely I'll use return)
该数组的长度是在运行时确定的,即用户敲击了一些小键盘键(可能我将使用return)
//input path to be analyzed
int n = 0;
while(scanf("%d",&input[n])==1){
//??
}
}
Input: 输入:
Then these values are stored in the array a as: 然后将这些值存储为数组a:
I also need proper error checking of course. 我当然也需要适当的错误检查。
This is a basic problem im sure however I'm unable to solve it. 我肯定这是一个基本问题,但是我无法解决。
Thanks! 谢谢!
Im thinking ill need a while loop however im unsure how to use scanf to both terminate the loop, initilize the array and input the values. 我认为我需要一个while循环,但是不确定如何使用scanf终止循环,初始化数组并输入值。
You can do it as follows: 您可以按照以下步骤进行操作:
int main()
{
char ch;
int i=0;
int input[100000]; //Or dynamically allocate
while(scanf("%c",&ch) && (ch!='\n')){
if(ch==' ') continue;
input[i++]=ch - '0';
printf("%d ",input[(i-1)]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.