Answer to Question #207212 in C for Ali khan

Question #207212

Write a program to carry out the following:

(a) Read a text file ‘INPUT.TXT’

(b) Print each word in reverse order

Example,

Input: PAKISTAN IS MY COUNTRY

Output: NATSIKAP SI YM YRTNUOC

Assume that each word length is maximum of 10 characters and each word is 

separated by newline/blank characters.


1
Expert's answer
2021-06-16T09:24:11-0400
INPUT.txt file:

PAKISTAN IS MY COUNTRY


C code:


#include <stdio.h>
#include <stdlib.h> 
#include <string.h>




int main() {
	char text[1000];
	char reverseWord[100];
	int i=0;
	char* word;
	int j;
	FILE *fptr;
	if ((fptr = fopen("INPUT.txt", "r")) == NULL) {
		printf("Error! File cannot be opened.");
		exit(1);
	}
	while ((text[i++] = fgetc(fptr)) != EOF);


	text[i-1]='\0';


	fclose(fptr);
	printf ("Input text: \n%s\n\n",text);
	word = strtok(text," ");
	printf ("\nText in reverse order: \n");
	while (word != NULL){
		j=0;
		for (i = strlen(word) - 1; i >= 0; i--)
		{
			reverseWord[j] = word[i];
			j++;
		}
		reverseWord[j] = '\0';
		printf ("%s ",reverseWord);
		word = strtok (NULL, " ");
	}


	free(word);
	getchar();
	getchar();
	return 0;
}








Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS