Reputation: 132
I have a text file, lets call it numbers.txt, and I need to scan it into an array.
numbers.txt (below is what is inside)
8 2 5 9 10 4 11 -1
The special value -1 indicates the end of the list.
I'm kinda confused on how to get it into my array. I know I need a loop, but can't put my head around it. Also, I am not scanning the file within the program, I am doing it within the terminal.
taylor> file < numbers.txt
So I would set it up like the user is inputting it.
int main()
{
int numbers[50];
int n, i;
//scanf("%i", &n)
for(i = 0; i < 50; i++)
{
//not sure what to do
}
}
Upvotes: 1
Views: 520
Reputation: 16540
the posted code does not compile! it is missing the #include
statements
Here is a version of the code that:
#include
statements-1
exits the read loopand now the code
#include <stdio.h> // scanf(), perror()
#include <stdlib.h> // exit(), EXIT_FAILURE
#define MAX_NUMBERS 50
int main( void )
{
int numbers[ MAX_NUMBERS];
int i;
//scanf("%i", &n)
for(i = 0; i < MAX_NUMBERS; i++)
{
if( 1 != scanf( "%d", &numbers[i] ) )
{
perror( "scanf for number failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
if( -1 == numbers[i] ) break;
}
}
Upvotes: 0
Reputation: 153457
OP needs to account for many stopping conditions.
Data read is -1 per OP's deleted comment "... I want it to stop once it its -1. So like while(!=-1)
run the loop. I could do that with if statements as well." . This is detectable by testing the value read.
Only up to 50 numbers. Test the count of numbers read.
Not more input (end-of-file). This is detectable by testing the scanf()
return value of EOF
.
Rare input error. (example, keyboard cable broke.) This is also detectable by testing the scanf()
return value of EOF
.
If the input was non-numeric. This is detectable by testing the scanf()
return value of 0.
If the input text was in range of int
. Detection for this is not shown below.
Unclear if all data needs to be on one line, so detecting a '\n'
is needed. Detection for this is not shown below.
Example
int main()
{
int numbers[50];
int i = 0;
for( ; i < 50; i++) {
int n;
int conversion_count = scanf("%i", &n);
if (conversion_count != 1) {
break; // End-of-file, input error, non-numeric input
}
if (n == -1) {
break;
}
numbers[i] = n;
}
printf("%d numbers read.\n", i);
}
Upvotes: 2