Sorting strings from the text file
Given a text file “file.txt” that consists of strings, the task is to sort all the strings in alphabetical order in that text file.
Approach: The idea is to use the concept of File Handling and a text file(say file.txt) that contains all the strings. Below are the steps:
- Create the file using fopen() and insert names into the file using fprintf().
- Close the file using fclose().
- Reopen the file for reading the names.
- Read or scan the names from the file using fscanf() and store it in a vector of strings.
- Sort the given string stored in the vector using the sort() function.
- Now, insert the sorted string in that file and print it.
Below is the implementation of the above approach:
C++
// C++ program to sort given array // of string stored in a file #include <bits/stdc++.h> #include <cstdlib> #include <cstring> #include <fstream> using namespace std; // Driver Code int main() { int N, i, j; // File pointer to open file FILE * f; // fopen() for creating of a file f = fopen ( "file.txt" , "w" ); // Input number of strings // to be inserted in file cin >> n; vector< int > name(N); // Insert the strings into file for (i = 0; i < n; i++) { // Insert names in file cin >> name[i]; // Writing into the file fprintf (f, "%s" , name[i]); } // Close the file fclose (f); // Reopening in read mode f = fopen ( "file.txt" , "r" ); // Check does file exist or not if (f == NULL) { cout << "File doesn't exist!" ; return 0; } // Read the file until it // encounters end of line while (! feof (f)) { fscanf (f, "%s" , name[i]); i++; } n = i - 1; // Sort the strings sort(name.begin(), name.end()); // Insert the strings into file // after sorting for (i = 0; i < n; i++) { // Write into the file fprintf (f, "%s" , name[i]); } // Print the sorted names for (i = 0; i < n; i++) { cout << name[i] << '\n' ; } return 0; } |
Input File:
Output File:
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.