KUMA
KUMA

Reputation: 27

C Reading numbers from text file into an array and using numbers for other function

I'm new so please excuse my lack of proper coding language.

I have a text file that reads:

80 83 82 81
94 95 87 86
86 90 78 95

How can I read the text file that puts those into an array and then in another function that multiplies the first 2 numbers (I plan on doing much more calculations).

Upvotes: 1

Views: 563

Answers (1)

Barr J
Barr J

Reputation: 10929

to read the file and put the numbers in an array use fscanf():

 FILE *myFile;
myFile = fopen("somenumbers.txt", "r");

//read file into array
int numberArray[16];
int i;

for (i = 0; i < 16; i++) //instead of 16, your numbers length
{
    fscanf(myFile, "%1d", &numberArray[i]);
}

myFunction(numberArray); //call the multiplication method

to pass the array and multiple the first two numbers:

int myFunction(int param[]) {
     return param[0] * param[1];
}

Upvotes: 2

Related Questions