There's always been a question. If you do not know the number of numbers when entering a row of numbers, the easiest way to do this is to receive the characters and turn them into numbers, but that's too much trouble.
Today on the Internet to check the next, said you can use the UNGETC () function to send the characters back to the input stream, summarized here
In addition to the accidental resolution of other problems previously encountered, but also found in debugging code, with this code can be used in addition to characters other than spaces as separators, and the length of the delimiter can be very long: such as input 12qwertyuiop34asdfghjkl123,23zxc45 The last array to get is: a[0]=12,a[1]=34,a[2]=123,a[3]=23,a[4]=45
First put the code:
1#include <stdio.h>2#include <ctype.h>3 intMain ()4 {5 inta[ +];6 CharC;7 intI=0;8 intn=0;9 while((C=getchar ())! ='\ n')Ten { One if(IsDigit (c)) A { -UNGETC (C,stdin);//send C back to the input stream -scanf"%d", &a[n++]); the } - } - for(i=0; i<n;i++) - { +printf"%d", A[i]); - } + return 0; A}
To illustrate, it is possible to reduce the number of loops by placing a 14-line scanf function outside the IF statement when using a space as a separator
But if you use other symbols as delimiters, you can only put them in an if statement, or you will get an error.
Here is another question, how to know the length of the array at the beginning, how much is the definition appropriate?
- If you can estimate the size of an array beforehand, you can define a bit larger than the estimated value.
- If unpredictable, my solution would be to use a linked list, but it would be impossible to use some of the features of the array, such as the possibility of spending a lot of time looking for some of the underlying data
- In addition, I think of the method of sacrificing storage space, first use the linked list to save the data, and record the number. If you need to use subscript to access data more than once, you can dynamically allocate a piece of memory to store the data, release the original linked list, or retain it as needed.
- Besides, I didn't think of any good way ...
C Input line unknown number of numbers in the array