Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have an input file that is just Apple Banana Pear etc. all on different lines

ID: 3796615 • Letter: I

Question

I have an input file that is just

Apple Banana Pear etc. all on different lines

and I need to use a loop to go line-by-line assigning each string to a variable, and then later passing that string to other functions. I am doing this by using fscanf (required). Currently I have in my main()

and

If I run the printf statement from the input function, I get the whole string perfectly. If I run it from main, I just get "A". It does not later change to "B" when doing the banana line, although the printf statement in the input function prints out correctly. What gives and how can I get the name var printed out in my main(), and later be able to pass that var?

Explanation / Answer

//This sample file will demonstrates how to read text from a file from input and main method

//sample.c
#include<stdio.h>
#include<conio.h>
void input(FILE *fp1, char *name);
int main()
{

   //character is a pointer that stores the address of variable
   //here name is a pointer that is assigned 20 bytes memory space
   //pointed by name pointer
   char *name=new char[20];
   int i;      
   //take fileName as sample
   char *fileName="fruits.txt";
   //open the file in read mode
   FILE* fp1=fopen(fileName,"r");
   int fileLength=3;
   for (i=0; i<fileLength; i++)
   {
       //calling input function
       input(fp1, name);
       printf("Printing line from main funtion ");
       printf("%s ", name);
   }

   //close file stream fp1
   fclose(fp1);
   getch();
   return 0;
}

//input funtion
void input(FILE *fp1, char *name)
{
   //using fgets function that name reads 20 byte character
   //value pointed by name in fp1 file stream
    fgets(name,20,fp1);
   //print from input function
   printf("Printing line from input funtion ");
    printf("%s ", name);
}


------------------------------------------------------------------------------------------

Sample Output:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote