简体   繁体   中英

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)

EXAMPLE

//input path to be analyzed
  int n = 0;
  while(scanf("%d",&input[n])==1){
    //??
  }
}

Input:

3 2 1 3 4 5 (return)

Then these values are stored in the array a as:

[3, 2, 1, 3, 4, 5]

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.

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)]);
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM