So I was given a code in class to help with this assignment...Ihave modified it
ID: 3619017 • Letter: S
Question
So I was given a code in class to help with this assignment...Ihave modified it a bit but I just read the part where I have toprompt the user for a filename....In the same folder as this C file I have a txt file with the infoneeded...
How can I change this code so I can ask a user for a txt file toread?
#include <stdio.h>
int main()
{
//variables
FILE* pFile = NULL;
int nsid = 0;
char lastname[255];
float midterm = 0;
float final = 0;
float wavg = 0;
char decision = 0;
// r means open for reading can only open for reading nowriting
pFile = fopen("input.txt", "r");
if (pFile == NULL)
{
printf ("Error opening file! ");
return -1;
}
printf("%-10s %-10s %-10s %-10s ", "nsid" , "lastname" ,"midterm" , "final");
while (!feof(pFile))
{
// -10s aligns the columns
fscanf(pFile, "%d %s %f %f ", &nsid,lastname, &midterm, &final);
printf("%-10d %-10s %-10f %-10f ", nsid,lastname, midterm, final);
}
fclose(pFile);
return 0;
}
Explanation / Answer
please rate - thanks #include int main() { //variables FILE* pFile = NULL; int nsid = 0; char lastname[255]; charfilename[80]; float midterm = 0; float final = 0; float wavg = 0; char decision = 0; // r means open for reading can only open for reading nowriting printf("Enter the filename forinput: "); scanf("%s",&filename); pFile = fopen(filename, "r"); if (pFile == NULL) { printf ("Error opening file! "); return -1; } printf("%-10s %-10s %-10s %-10s ", "nsid" , "lastname" ,"midterm" , "final"); while (!feof(pFile)) { // -10s aligns the columns fscanf(pFile, "%d %s %f %f ", &nsid,lastname, &midterm, &final); printf("%-10d %-10s %-10f %-10f ", nsid,lastname, midterm, final); } fclose(pFile); return 0; }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.