C Programming: Remove the spaces between two words of its content
C String: Exercise-29 with Solution
Write a program in C to read a file and remove the spaces between two words of its content.
Sample Solution:
C Code:
#include<stdio.h>
#include<ctype.h>
int main() {
FILE * pfile; // File pointer to handle file operations
int a; // Variable to store characters read from the file
printf("\n Remove the spaces between two words :\n");
printf("-----------------------------------------\n");
// Open a file named "file.txt" in read mode
pfile = fopen("file.txt", "r");
printf(" The content of the file is :\n The quick brown fox jumps over the lazy dog\n\n");
printf(" After removing the spaces the content is : \n");
// Check if file is opened successfully
if (pfile) {
// Read characters from file until End of File (EOF) is reached
do {
a = fgetc(pfile); // Read a character from the file
// Check if the character is printable (not a space or control character)
if (isgraph(a)) {
putchar(a); // Print the character if it's not a space or control character
}
} while (a != EOF); // Repeat until End of File (EOF) is encountered
fclose(pfile); // Close the file
}
printf("\n\n");
return 0; // Return 0 to indicate successful execution of the program
}
Sample Output:
Remove the spaces between two words : ----------------------------------------- The content of the file is : The quick brown fox jumps over the lazy dog After removing the spaces the content is : Thequickbrownfoxjumpsoverthelazydog
Flowchart :
C Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a program in C to check whether a letter is lowercase or not.
Next: Write a program in C to check whether a character is digit or not.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/c-programming-exercises/string/c-string-exercise-29.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics