Write a program in C that reads in a text file using scanf, that parses the inpu
ID: 3757448 • Letter: W
Question
Write a program in C that reads in a text file using scanf, that parses the input which is two integers per line seperatated by a space and filter the first three valid lines of input into three variables.
For example the text file may look like:
10 5
11 20
5 8
8 5
If the bound are x(left column) has to be greater than 20 and y(right column) has to be greater than 20 then put the first three valid lines of input into variables x1,x2,x3 & y1,y2,y3. The input is valid only if both the x and y are valid. If the text file is read through and there is not 3 valid lines of input, exit the program.
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
// main function definition
int main()
{
// Declares two arrays X and Y of size 3 to store 3 valid data read from file
int X[3], Y[3];
// To store read x and y data from file
int x, y;
// Number counter
int counter = 0;
// To store file name
char fileName[20];
// File pointer declared
FILE *fp;
// Accepts file name
printf(" Enter the file name: ");
scanf("%s", fileName);
// Opens the file for reading
fp = fopen(fileName, "r");
// Checks if the file cannot be opened display error message and stop
if(!fp)
{
printf("ERROR: The file %s cannot be opened", fileName);
exit(0);
}// End of if condition
// Loops till end of the file
while(!feof(fp))
{
// Checks if counter is 3 then come out of the loop
if(counter == 3)
break;
// Reads two integer data from file and stores it in x and y
fscanf(fp, "%d %d", &x, &y);
// Checks if x and y both are greater than 20
if(x > 20 && y > 20)
{
// Assigns x and y value at counter index position of X and Y array
X[counter] = x;
Y[counter] = y;
// Increase the record counter by one
counter++;
}// End of if condition
}// End of while loop
// Close the file
fclose(fp);
// Checks if counter value is 3 then display data
if(counter == 3)
printf(" x1 = %d y1 = %d x2 = %d y2 = %d x3 = %d y3 = %d ", X[0], Y[0], X[1], Y[1], X[2], Y[2]);
// Otherwise display error message
else
printf(" Unable to get 3 valid values for X and Y");
}// End of main function
Sample Output 1:
Enter the file name: checkValid1.txt
Unable to get 3 valid values for X and Y
Sample Output 2:
Enter the file name: checkValid2.txt
x1 = 22 y1 = 25
x2 = 35 y2 = 28
x3 = 28 y3 = 45
checkValid1.txt file contents
10 5
11 20
5 8
8 5
checkValid2.txt file contents
22 25
11 20
35 28
28 45
12 23
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.