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

Write a program using text file I/O to open any file and print out all of the in

ID: 3638551 • Letter: W

Question

Write a program using text file I/O to open any file and print out all of the integers in the file, and their sum. You should input one character at a time, and convert contiguous characters into integers.

=> Prompt for a name and open the file.
=> Scan the file, and loop through each character, ignoring any character that is not a digit or a -sign.
    ~ If it is a - sign, store that information so the integer will be negative.
    ~ If it is a digit, set a currentInt value to the numeric value of that digit, and loop as long as there are more digits, multiplying currentInt by 10 and adding the numeric value of the next digit.
=> After the loop exits, multiply by -1 if it is negative, print it out and add it to a total.
Be careful that you don't try to read past the end of the file.

Explanation / Answer

#include<stdio.h>

int main()

{

int i =0, sign=0, sum=0;

char filename[200];

printf("Enter File Name : ");

scanf("%s",filename);

char c;

FILE * f ;

f=fopen(filename,"r");

if(f!=NULL) printf("Opening File... ");
while((c=fgetc(f))!=EOF)

{

if(c>=48&&c<=57)

{ i=i*10+(int)c-48; }

else if(c=='-') { sign = 1; }

else if(c==' '||c==' ')

{ if(sign==1) i = -i; printf("%d ",i);

sum+=i; sign=0; i=0; }

}

if(sign==1) i=-i;

printf("%d",i);

sum+=i;

printf(" Sum = %d ",sum);

return 0;

}

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