问题
Say I have a file with the numbers: 1 2 3 4 5 6 7 8 9 10 -1
I want to read in that file and store all the values of that file, stopping at the control variable -1.
So if I printed that array to another file it would look like: 1 2 3 4 5 6 7 8 9 10
This gives me all the numbers, but it has -1 included. How can I drop off the -1?
int arr[100];
int n;
while (scanf("%d",&arr[n]) > 0)
n++;
回答1:
You cannot add the > 0 condition: this would give you undefined behavior. In order to ignore the negative one, you could add a separate check inside the loop, after reading the number, like this:
while (scanf("%d", &arr[n]) != EOF) {
if (arr[n] > 0) {
n++;
}
}
Since the array arr has fixed size, it would be a good idea to guard against overruns, like this:
while (n < 100 && scanf("%d", &arr[n]) != EOF) {
if (arr[n] > 0) {
n++;
}
}
This loop would stop if you reach 100 before the file ends. Note that you also need to initialize n to zero before the loop to avoid undefined behavior.
Here is a demo on ideone.
回答2:
int arr[100];
int n;
int temp;
do
{
scanf("%d",&temp);
if(temp != -1)
{
arr[n] = temp;
}
n++;
}while(temp != -1 && n < 100);
来源:https://stackoverflow.com/questions/19914298/how-do-i-scan-in-numbers-to-an-array-from-a-file