what compiler are you using. I compiled and ran it with VC++ 6.0 and it worked ok for me. I changed the filename in the code below, so you will have to reset it if you copy this code.
If this doesn't work for you either, scatter some debug print() statements around so that you can trace the program's execution. Or learn to use a good debugger.
Code:
/*This program will input data into two parallel arrays from scores.txt.
*It will them print out the student's score according to their ID number.
*
*Input:
*Student Number
*
*Outputs:
*Student Number
*Mark of Student
*/
#include <stdio.h>
#define MAXIMUM 100
#define SENTINEL -99
/*Function Prototypes*/
int getData(int iId[], int Score[]);
int searchArray (const int iArray[], int iNum, int iTarget);
int main (void)
{
int iId[MAXIMUM], iScore[MAXIMUM]; /*Arrays*/
int iNum, iTarget, iPosition; /*Array Parameters*/
/*Call Function to get data*/
iNum = getData(iId, iScore);
if (iNum > MAXIMUM)
{
printf("Too much input data!\n");
return (-1);
}
printf("Enter a student number (-99 to quit): ");
scanf("%d", &iTarget);
while (iTarget != SENTINEL)
{
iPosition = searchArray (iId, iNum, iTarget);
if (iPosition == -1)
{
printf ("Not in Array!\n");
return(-1);
}
printf("Student number: %d\n", iId[iPosition]);
printf("Mark: %d\n\n", iScore[iPosition]);
printf("Enter a student number (or -99 to quit): ");
scanf("%d", &iTarget);
}
return (0);
}
/*****FUNCTIONS*****/
/*Function to input the data from the file into the arrays and print the data*/
int getData(int iId[], int iScore[])
{
int iStatus, iNum;
FILE *inp;
inp = fopen("scores.txt", "r");
if (inp == NULL)
{
printf("Unable to open file!\n");
return (-1);
}
iNum = 0;
iStatus = fscanf(inp, "%d %d", &iId[0], &iScore[0]);
while (iStatus == 2 && iNum < MAXIMUM)
{
iNum++;
iStatus = fscanf(inp, "%d %d", &iId[iNum], &iScore[iNum]);
}
fclose(inp); /*close the file*/
return (iNum); /*return number of ints read*/
}
/*Function to search array for student #*/
int searchArray (const int iId[], int iNum, int iTarget)
{
int iFound, iPosition;
/*Assume target has not been found*/
iFound = 0;
/*Loop until either target is found or we are at end of data*/
iPosition = 0;
while (iFound == 0 && iPosition < iNum)
{
if (iId [iPosition] == iTarget)
{
iFound = 1;
}
else
{
iPosition++;
}
}
if (iFound == 0)
{
return (-1);
}
else
{
return (iPosition);
}
}