Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to display the complete text one word per line in C language?
In C, displaying text one word per line involves reading words from a file and printing each word on a separate line. This can be accomplished by using file handling functions to read words and format the output appropriately.
Syntax
fscanf(file_pointer, "%s", word_buffer);
printf("%s<br>", word);
Example: Reading Words from File
The following program demonstrates how to display text one word per line by reading from a file −
Note: This example uses file operations. Create a text file named "input.txt" with some text content before running the program.
#include <stdio.h>
int main() {
FILE *fp;
char word[100];
/* Open file in read mode */
fp = fopen("input.txt", "r");
if (fp == NULL) {
printf("Error: Could not open file.<br>");
return 1;
}
printf("Text displayed one word per line:<br>");
/* Read words from file and print each on separate line */
while (fscanf(fp, "%s", word) != EOF) {
printf("%s<br>", word);
}
fclose(fp);
return 0;
}
Example: Using String Input
Here's an alternative approach that processes a string directly without file operations −
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "Welcome to TutorialsPoint Programming";
char *word;
printf("Original text: %s<br>", text);
printf("\nText displayed one word per line:<br>");
/* Use strtok to split string into words */
word = strtok(text, " ");
while (word != NULL) {
printf("%s<br>", word);
word = strtok(NULL, " ");
}
return 0;
}
Original text: Welcome to TutorialsPoint Programming Text displayed one word per line: Welcome to TutorialsPoint Programming
Key Points
- The
fscanf()function with"%s"format specifier reads words separated by whitespace. - The
strtok()function can split strings into tokens based on specified delimiters. - Always check if file operations are successful before proceeding with read operations.
- Each
printf("%scall prints a word followed by a newline character.
", word)
Conclusion
Displaying text one word per line in C can be achieved using file operations with fscanf() or string manipulation with strtok(). Both methods effectively separate words and format output with each word on its own line.
